| id | chat_gpt_response | question | badsmell_base | bad_smell_gpt | found_any | valid_bad_smell | bad_smell_in_base | bad_smell_not_in_the_base | bad_smell_not_found | index | index_base | url_github | nr_question | id_source_code | id_base |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2100 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inconsistent indentation 5. Duplicate code 6. Inconsistent naming convention | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class4 Inconsistent indentation5 Duplicate code6 Inconsistent naming convention | t | f | t | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 2100 | 13158 | ||
| 2217 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Long method 3. Feature envy 4. Switch statement 5. Magic numbers 6. Improper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Duplicate code2 Long method 3 Feature envy4 Switch statement 5 Magic numbers 6 Improper exception handling | t | f | t | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 2217 | 13539 | ||
| 2127 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 2127 | 13223 | ||
| 4088 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 4088 | 10777 | ||
| 3840 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 3840 | 9895 | ||
| 5759 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Long parameter list"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5759 | 14515 | |
| 3940 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 3940 | 10313 | ||
| 2013 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method, data class | t | t | t | data class | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2013 | 12755 | |
| 1906 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Conditional complexity 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Conditional complexity5 Feature envy | t | f | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 1906 | 12380 | ||
| 489 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void appendXmlComparison1(SQLBuffer buf, String op, FilterValue lhs, FilterValue rhs) { boolean castrhs = false; Class rc = Filters.wrap(rhs.getType()); int type = 0; if (rhs.isConstant()) { type = getJDBCType(JavaTypes.getTypeCode(rc), false); castrhs = true; } appendXmlExists(buf, lhs); buf.append(" ").append(op).append(" "); buf.append("$"); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("]' PASSING "); appendXmlVar(buf, lhs); buf.append(", "); if (castrhs) appendCast(buf, rhs, type); else rhs.appendTo(buf); buf.append(" AS \""); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("\")"); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 4865 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DB2Dictionary.java/#L682-L717 | 2 | 489 | 4865 | |
| 1446 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | blob, long method | t | t | t | blob | 0 | 10983 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 1 | 1446 | 10983 | |
| 1194 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 1194 | 10265 | ||
| 1746 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1746 | 11853 | ||
| 1118 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 9959 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1118 | 9959 | ||
| 577 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5782 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 577 | 5782 | ||
| 1204 | {"response":"YES I found bad smells","bad smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method | t | t | t | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 1204 | 10287 | ||
| 1010 | YES, I found bad smells the bad smells are: 1 - Long method 2 - Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | - Long method2 - Feature envy | t | f | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1010 | 9270 | ||
| 9 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 2 | 9 | 612 | |
| 5012 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Tight coupling 5. Magic numbers 6. Dead code 7. Exception handling 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method 2 Duplicate code 3 Feature envy 4 Tight coupling 5 Magic numbers 6 Dead code 7 Exception handling 8 Lack of comments/documentation | t | f | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 5012 | 13779 | ||
| 884 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method,2 Feature envy | t | f | t | 2. Feature envy | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 884 | 8035 | |
| 3902 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | Long method | t | f | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 2 | 3902 | 10217 | ||
| 866 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7932 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 866 | 7932 | ||
| 755 | YES I found bad smells. the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7047 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 | 2 | 755 | 7047 | |
| 4676 | YES I found bad smells the bad smells are: 1. Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance). 2. Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class). 3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain). 4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex). 5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code). 6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality). 7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance)2 Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class)3 Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain)4 Nested loops (there are nested for loops, which can decrease performance and make the code more complex)5 Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code)6 Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality)7 Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow) | t | f | t | which can indicate that it belongs in a different class).3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain).4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex).5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code).6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality).7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 4676 | 12504 | |
| 2781 | public boolean paramsLacking() { return pkixParams.getAnyPolicyInhibited() || pkixParams.getPolicyMappingInhibited() || pkixParams.isExplicitPolicyRequired() || pkixParams.isPolicyMappingInhibited() || pkixParams.isAnyPolicyInhibited() || !pkixParams.getPolicyQualifiersRejected() || !pkixParams.getInitialPolicies().isEmpty(); } YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Primitive obsession 5. Inappropriate intimacy 6. Inconsistent naming 7. Temporary field 8. Comments 9. Shotgun surgery 10. Lazy class 11. Data class 12. Data clumps 13. Speculative generality 14. Message chains 15. Brain overload 16. Large class 17. Deficient encapsulation 18. Combinatorial explosion 19. Extensive coupling 20. Divergent change 21. Inappropriate subclass 22. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method 2 Feature envy 3 Duplicate code 4 Primitive obsession 5 Inappropriate intimacy 6 Inconsistent naming 7 Temporary field 8 Comments 9 Shotgun surgery | t | f | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2781 | 1122 | ||
| 387 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 387 | 3944 | |
| 1951 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | data class, long method | t | t | f | data class | long method | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 1951 | 12534 |
| 276 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | long method, data class | t | t | t | data class | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 276 | 2964 | |
| 9 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method | t | t | t | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 1 | 9 | 612 | ||
| 1595 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Poor variable and method naming 4. Unnecessary commenting 5. Use of instanceof 6. Nested if/else blocks 7. Lack of proper comparison "strategy" 8. Unnecessary casting 9. Lack of clear separation of tasks/responsibilities 10. Possible code duplication 11. Missing error handling 12. Potential for null pointer exceptions 13. Lack of use of standard equals() method 14. Excessive amount of code wrapping | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method 2 Feature envy 3 Poor variable and method naming 4 Unnecessary commenting 5 Use of instanceof 6 Nested if/else blocks 7 Lack of proper comparison "strategy" 8 Unnecessary casting 9 Lack of clear separation of tasks/responsibilities | t | f | t | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 1595 | 11408 | ||
| 772 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 772 | 7285 | ||
| 1518 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11170 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 1518 | 11170 | ||
| 351 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | 1. long method | t | t | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 351 | 3600 | ||
| 2070 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 2070 | 13017 | ||
| 1615 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 1615 | 11472 | |
| 2607 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method | t | t | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 2607 | 15030 | ||
| 2177 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | 1. long method | t | t | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 2177 | 13408 | ||
| 345 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 1 | 345 | 3519 |
| 1043 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | 1. long method | t | t | t | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1043 | 9446 | ||
| 450 | {"output":"YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | 1. long method | t | t | f | long method | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 450 | 4392 | |
| 2166 | Yes, I found bad smells(the bad smells are: 1. Long method 2. Data class 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2166 | 13348 | ||
| 2652 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2652 | 15177 | ||
| 4359 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 4359 | 11504 | ||
| 1885 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting and whitespace (inconsistent use of tabs/spaces) 4. Mixing of logging and exception handling in same method 5. Catching generic Exception class instead of specific exceptions 6. Use of instanceof operator 7. Nested, complex logic 8. Lack of proper error handling and messaging 9. Code duplication 10. Poor variable naming 11. Unnecessary use of Hashmap and casting 12. Unused variables 13. Inefficient use of EntityManager 14. Nested try-catch blocks 15. Inconsistent use of brackets/indentation 16. Fragile code (e.g. using string literals instead of constants) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method 2 Feature envy3 Inconsistent formatting and whitespace (inconsistent use of tabs/spaces)4 Mixing of logging and exception handling in same method5 Catching generic Exception class instead of specific exceptions6 Use of instanceof operator7 Nested, complex logic 8 Lack of proper error handling and messaging9 Code duplication | t | f | t | complex logic 8. Lack of proper error handling and messaging9. Code duplication | 0 | 12293 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 1885 | 12293 | |
| 762 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method, data class | t | t | t | data class | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 762 | 7113 | |
| 2257 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Deeply nested code, 6 Inconsistent formatting, 7 Coupling, 8 Lava flow code, 9 Cognitive complexity | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 2257 | 13693 | |
| 1262 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | long method | t | t | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1262 | 10513 | ||
| 5773 | {"response":"YES I found bad smells","bad smells are:":"1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5773 | 14885 |
| 4398 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 4398 | 11629 | |
| 1528 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 1528 | 11199 | |
| 1887 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12299 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 1887 | 12299 | ||
| 1173 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1173 | 10199 | ||
| 517 | { "message": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | long method | t | t | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 1 | 517 | 5350 | ||
| 4086 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 4086 | 10775 | ||
| 4232 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | long method | t | t | t | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 4232 | 11137 | ||
| 743 | { "output": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 743 | 6978 | |
| 2519 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 2519 | 14706 | |
| 1544 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long Method | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1544 | 11245 | ||
| 1282 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1282 | 10603 | ||
| 2422 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Feature envy2 Long method | t | f | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2422 | 14435 | ||
| 767 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 767 | 7227 | |
| 745 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 745 | 7007 | |
| 767 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 767 | 7227 | ||
| 35 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | 1. long method | t | t | t | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 35 | 743 | ||
| 1781 | YES I found bad smells the bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method, Feature envy | t | f | t | Feature envy. | 0 | 11962 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 1781 | 11962 | |
| 1716 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long Method | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1716 | 11781 | ||
| 732 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 732 | 6885 | ||
| 2387 | {"response": "YES I found bad smells. the bad smells are: 1. Blob, 2. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | 1. blob, 2. long method | t | t | t | 1. blob | 0 | 14351 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2387 | 14351 | |
| 1352 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method | t | t | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1352 | 10761 | ||
| 2640 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Message chain 5. Unnecessary conditional logic 6. Inconsistent variable naming conventions 7. Use of system exceptions 8. Inappropriate handling of errors or exceptions 9. Mixing of business logic and error handling code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Duplicate code3 Feature envy4 Message chain5 Unnecessary conditional logic6 Inconsistent variable naming conventions7 Use of system exceptions8 Inappropriate handling of errors or exceptions9 Mixing of business logic and error handling code | t | f | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2640 | 15143 | ||
| 2391 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 2391 | 14362 | ||
| 783 | {"response": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | long method | t | t | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 783 | 7493 | ||
| 787 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 787 | 7509 | ||
| 1497 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1497 | 11126 | ||
| 254 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 254 | 2738 | |
| 2404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 2404 | 14385 | ||
| 2260 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 2260 | 13711 | |
| 2530 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 2 | 2530 | 14736 | |
| 2055 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | long method | t | t | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2055 | 12939 | ||
| 1694 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | 'Long Method' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',L,o,n,g," ",M,h,o,d,'} | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1694 | 11718 |
| 1225 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1: long method | t | t | t | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 1225 | 10351 | ||
| 1305 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 1305 | 10673 | |
| 1561 | YES I found bad smells the bad smells are: 1. Long method 2. Inconsistent indentation 3. Empty catch statement 4. Magic numbers 5. Use of switch statement 6. Use of multiple if/else statements 7. Use of null check syntax 8. Code duplication/repetition 9. Poor variable naming 10. Mixing of logic and data manipulation 11. Unnecessary commenting 12. Nested conditionals 13. Hard-coded values 14. Mix of different coding styles/mixing of languages (Java and protocols) 15. Use of bitwise operations (bitField0_) 16. Lack of proper error handling/reporting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Inconsistent indentation3 Empty catch statement4 Magic numbers5 Use of switch statement6 Use of multiple if/else statements7 Use of null check syntax8 Code duplication/repetition9 Poor variable naming | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 1561 | 11308 | ||
| 605 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Poor naming conventions for variables and methods 6. Nested conditional statements 7. Lack of comments or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Poor naming conventions for variables and methods6 Nested conditional statements7 Lack of comments or documentation | t | f | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 605 | 6050 | ||
| 1972 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 1972 | 12611 | ||
| 1207 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 1207 | 10290 | ||
| 469 | YES I found bad smells" YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 469 | 4555 | ||
| 2574 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14912 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2574 | 14912 | ||
| 1637 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 11527 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 1637 | 11527 | |
| 861 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 861 | 7903 | ||
| 2309 | YES, I found bad smells the bad smells are: 1.Long method, 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2Duplicated code, 3Magic number, 4Inappropriate comments, 5Lazy class, 6Feature envy | t | f | t | 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2309 | 14095 | |
| 4239 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 4239 | 11159 | |
| 1693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11716 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 1693 | 11716 | ||
| 1431 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method | t | t | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1431 | 10955 | ||
| 1004 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | 1. long method | t | t | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1004 | 9254 | ||
| 2011 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method, 2Feature envy, 3Magic number, 4Multiple nested if statements, 5Use of a mixture of data types without clear reason, 6Inconsistent indentation, 7Duplicate code, 8Missing comments, 9Poor error handling | t | f | t | 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2011 | 12750 | |
| 1314 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1314 | 10686 | ||
| 884 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 884 | 8035 | |
| 2696 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2696 | 15319 | ||
| 747 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 747 | 7016 | ||
| 581 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method, data class | t | t | t | data class | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 581 | 5786 | |
| 1744 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long Method | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 1744 | 11849 | ||
| 1200 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication (in the if statements for different subclasses of colWidth) 4. Inconsistent formatting (spacing, use of braces) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Code duplication (in the if statements for different subclasses of colWidth)4 Inconsistent formatting (spacing, use of braces) | t | f | t | use of braces) | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1200 | 10279 | |
| 2006 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 2006 | 12721 | ||
| 1317 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10691 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1317 | 10691 | |
| 1033 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | long method | t | t | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1033 | 9391 | ||
| 224 | { "message": "YES I found bad smells", "bad smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 1 | 224 | 2418 | |
| 2640 | { "output": "YES, I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2640 | 15143 | ||
| 2138 | after setting up and validating the experiment. * * * * @param airavataExperiment * @return The Experiment * @throws org.apache.airavata.registry.api.exception.RegistryServiceException */APPLICATION_LOGIC, YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 2138 | 13259 | ||
| 1604 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1604 | 11442 | |
| 474 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean supportsParameter(MethodParameter parameter) { if (!super.supportsParameter(parameter)) { return false; } Class type = parameter.getParameterType(); if (!type.isInterface()) { return false; } // Annotated parameter if (parameter.getParameterAnnotation(ProjectedPayload.class) != null) { return true; } // Annotated type if (AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null) { return true; } // Fallback for only user defined interfaces String packageName = ClassUtils.getPackageName(type); return !IGNORED_PACKAGES.stream().anyMatch(it -> packageName.startsWith(it)); } |
long method | 1. long method | t | t | f | long method | 0 | 4578 | https://github.com/spring-projects/spring-data-commons/blob/48c9297118e18273a0a3dfe3cf2f9a8ffd8fdca7/src/main/java/org/springframework/data/web/ProxyingHandlerMethodArgumentResolver.java/#L88-L115 | 1 | 474 | 4578 | |
| 366 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 366 | 3740 |
| 3806 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | long method | t | t | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3806 | 9657 | ||
| 1595 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 1595 | 11408 | |
| 3334 | {"message": "YES I found bad smells, the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method | t | t | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 3334 | 6247 | ||
| 1991 | YES, I found bad smells The bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Magic numbers (specific values used without explanation) 5. Primitive obsession (using basic data types instead of creating custom classes for data) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Duplicated code2 Long method3 Feature envy4 Magic numbers (specific values used without explanation)5 Primitive obsession (using basic data types instead of creating custom classes for data) | t | f | t | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1991 | 12682 | ||
| 650 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 650 | 6383 | ||
| 715 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 715 | 6821 | |
| 2575 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | 1. long method | t | t | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2575 | 14915 | ||
| 1901 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 1901 | 12362 |
| 1897 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 1897 | 12341 | ||
| 1136 | YES I found bad smells the bad smells are: 1. long method, 2. feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method, 2 feature envy | t | f | t | 2. feature envy | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1136 | 10058 | |
| 3912 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 3912 | 10243 | ||
| 2342 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 2342 | 14179 | ||
| 1859 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting 4. Resource leak - the code is not properly handling and closing resources such as files or connections 5. Potential NullPointerException in line 36 6. Magic numbers - hardcoded values in the code that are not properly explained or documented 7. Possible duplicate code 8. Overcomplicated code - the use of reflection to set caller context could be simplified 9. Lack of exception handling or error checking 10. Possible poor naming of variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2 Feature envy3 Inconsistent formatting 4 Resource leak - the code is not properly handling and closing resources such as files or connections 5 Potential NullPointerException in line 36 6 Magic numbers - hardcoded values in the code that are not properly explained or documented 7 Possible duplicate code 8 Overcomplicated code - the use of reflection to set caller context could be simplified 9 Lack of exception handling or error checking | t | f | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1859 | 12219 | ||
| 795 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | long method | t | t | t | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 1 | 795 | 7555 | ||
| 1538 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1538 | 11226 | |
| 5490 | YES I found bad smells. the bad smells are: 1. Long method, 2. Data class. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method, 2 Data class | t | f | t | 2. Data class. | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5490 | 1877 | |
| 544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 544 | 5546 | ||
| 2450 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2450 | 14505 | |
| 1145 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 1145 | 10111 | ||
| 1041 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | long method | t | t | t | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1041 | 9429 | ||
| 506 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | 1. long method | t | t | f | long method | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 506 | 5141 | |
| 295 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 295 | 3109 | ||
| 2673 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2673 | 15225 | ||
| 2089 | { "response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13117 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 2089 | 13117 | |
| 743 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 743 | 6978 | ||
| 1991 | {"response": "YES I found bad smells", "detected bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1991 | 12682 | |
| 1006 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1006 | 9258 | |
| 353 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | long method | t | t | t | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 353 | 3634 | ||
| 1790 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | 'Long Method', 'Feature Envy' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',F,e,a,t,u,r,e," ",E,n,v,y,'} | {',L,o,n,g," ",M,h,o,d,',","," ",',F,a," ",n,v,y,'} | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 1790 | 11987 |
| 3786 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive conditional complexity 4. Code duplication 5. Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy3 Excessive conditional complexity4 Code duplication5 Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | t | f | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 3786 | 9536 | ||
| 5756 | YES I found bad smells the bad smells are: 1.Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long Method | t | f | t | 0 | 14501 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5756 | 14501 | ||
| 2343 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | data class, long method | t | t | t | data class | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 2343 | 14182 | |
| 2001 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | long method | t | t | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 2001 | 12710 | ||
| 1651 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 1651 | 11579 | |
| 369 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 369 | 3819 | ||
| 715 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Comments as code 4. Magic numbers 5. Indecent exposure 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method2 Duplicate code3 Comments as code4 Magic numbers5 Indecent exposure6 Feature envy | t | f | t | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 715 | 6821 | ||
| 374 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 374 | 3864 | ||
| 2013 | YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code (similar code blocks for different parameters) 3. Data class (the method is only performing data validation, which could be separated into its own class) 4. Feature envy (the use of a different helper class for extracting data) 5. Long parameter list (the method has a large number of parameters) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Repetitive code (similar code blocks for different parameters)3 Data class (the method is only performing data validation, which could be separated into its own class)4 Feature envy (the use of a different helper class for extracting data)5 Long parameter list (the method has a large number of parameters) | t | f | t | which could be separated into its own class)4. Feature envy (the use of a different helper class for extracting data)5. Long parameter list (the method has a large number of parameters) | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2013 | 12755 | |
| 2259 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method | t | t | t | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 2259 | 13703 | ||
| 1654 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 1654 | 11585 | |
| 2645 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method | t | t | t | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2645 | 15150 | ||
| 1926 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1926 | 12438 | ||
| 997 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (SUGGEST_PLACE) 3. Repeated code 4. Code duplication (calling mLocator.getLoadStatus().name() twice) 5. Inconsistent formatting (explicitly declaring interface type in generic) 6. Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList);) 7. Nested callbacks/functional complexity 8. Hard-coded values (.name() in if statement) 9. Non-descriptive variable names (suggestionsFuture) 10. Negative conditional statements (!mLocator.getLocatorInfo().isSupportsSuggestions()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Magic numbers (SUGGEST_PLACE)3 Repeated code4 Code duplication (calling mLocatorgetLoadStatus()name() twice)5 Inconsistent formatting (explicitly declaring interface type in generic)6 Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFutureget(); showSuggestedPlaceNames(mSuggestionsList);)7 Nested callbacks/functional complexity8 Hard-coded values (name() in if statement)9 Non-descriptive variable names (suggestionsFuture) | t | f | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 997 | 9139 | ||
| 2166 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2166 | 13348 | ||
| 1680 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long Method | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 1680 | 11666 | ||
| 880 | YES I found bad smells the bad smells are: 1. Long method 2. Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath) 3. The use of abbreviations (wd, dt, cv) 4. Single letter variable names (f, b, os) 5. Nested loops and conditionals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath)3 The use of abbreviations (wd, dt, cv)4 Single letter variable names (f, b, os)5 Nested loops and conditionals | t | f | t | consumerHeaderValue, bundleClassPath)3. The use of abbreviations (wd, dt, cv)4. Single letter variable names (f, b, os)5. Nested loops and conditionals | 0 | 8016 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 880 | 8016 | |
| 3694 | { "output": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | 1. long method | t | t | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 3694 | 8659 | ||
| 1688 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent indentation 4. Magic numbers 5. Lack of meaningful variable names 6. Inappropriate or excessive use of comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy3 Inconsistent indentation4 Magic numbers5 Lack of meaningful variable names6 Inappropriate or excessive use of comments | t | f | t | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 1688 | 11692 | ||
| 1986 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method | t | t | t | 0 | 12657 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1986 | 12657 | ||
| 1548 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1548 | 11258 | ||
| 195 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 1 | 195 | 2234 | ||
| 1262 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1262 | 10513 | ||
| 1152 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1152 | 10133 | |
| 309 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3204 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 2 | 309 | 3204 | |
| 2520 | { "message": "YES I found bad smells", "bad smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method | t | t | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 2520 | 14709 | ||
| 2254 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2254 | 13687 | ||
| 581 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method | t | f | t | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 581 | 5786 | ||
| 1298 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method, 2Magic numbers, 3Complex code, 4Duplicated code, 5Exception handling within a loop, 6Use of abbreviations in method name, 7Consider splitting up the method into smaller methods | t | f | t | 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | 0 | 10639 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 1298 | 10639 | |
| 1428 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells_are": [ "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | bad_smells_are: long method | t | t | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 1428 | 10949 | ||
| 1140 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10089 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 2 | 1140 | 10089 | ||
| 2571 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | long method | t | t | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 2571 | 14900 | ||
| 1363 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1363 | 10780 | |
| 270 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method | t | t | t | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 1 | 270 | 2901 | ||
| 2703 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Duplicate code, 3 Indecent exposure, 4 Inappropriate intimacy, 5 Feature envy | t | f | t | 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | 0 | 15335 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 2703 | 15335 | |
| 1513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1513 | 11161 | ||
| 4232 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy 3. Poor exception handling 4. Overuse of if/else statements 5. Mixing of responsibilities (e.g. handling both proxy and transaction logic in one method) 6. Poor variable naming (e.g. "target", "isNewEm") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long methods2 Feature envy3 Poor exception handling 4 Overuse of if/else statements 5 Mixing of responsibilities (eg handling both proxy and transaction logic in one method) 6 Poor variable naming (eg "target", "isNewEm") | t | f | t | "isNewEm") | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 4232 | 11137 | |
| 2419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if statement checking for targetType) 4. Null checks 5. Catching throwable instead of specific exception 6. Hardcoding class names and checking for specific class name (String editorName = targetType.getName() + "Editor") 7. Not following naming conventions (targetType instead of targetClass) 8. Use of two return statements within one method (line 10 and line 21) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy3 Duplicate code (in the if statement checking for targetType)4 Null checks5 Catching throwable instead of specific exception6 Hardcoding class names and checking for specific class name (String editorName = targetTypegetName() + "Editor")7 Not following naming conventions (targetType instead of targetClass)8 Use of two return statements within one method (line | t | f | t | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 2419 | 14427 | ||
| 2703 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | long method, blob | t | t | t | blob | 0 | 15335 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 2703 | 15335 | |
| 2110 | YES I found bad smellsthe bad smells are: 1. Long method 2. Repeated code (sentryClient.grantRoleToGroups() and sentryClient.revokeRoleFromGroups()) 3. Mixing of concerns (roles and groups being handled in the same method) 4. Lack of proper error handling (catch block does not handle all types of exceptions) 5. Inconsistent naming conventions (camel case and underscore usage) 6. Using generic exception types instead of specific ones 7. Lack of comments/documentation to explain the purpose of the code and its functionality. 8. Nested try-catch blocks 9. Tight coupling (dependency on specific implementation of SentryClient) 10. Code duplication (grant/revoke functionality is repeated for each role) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Repeated code (sentryClientgrantRoleToGroups() and sentryClientrevokeRoleFromGroups())3 Mixing of concerns (roles and groups being handled in the same method)4 Lack of proper error handling (catch block does not handle all types of exceptions)5 Inconsistent naming conventions (camel case and underscore usage)6 Using generic exception types instead of specific ones7 Lack of comments/documentation to explain the purpose of the code and its functionality8 Nested try-catch blocks9 Tight coupling (dependency on specific implementation of SentryClient) | t | f | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 2110 | 13182 | ||
| 662 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 662 | 6455 | ||
| 195 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 2 | 195 | 2234 | ||
| 2359 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method | t | f | t | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 2359 | 14234 | ||
| 1552 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Nested conditionals 4. Inconsistent variable naming 5. Unused code 6. Inappropriate naming (e.g. delegate, parent) 7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method2 Feature Envy3 Nested conditionals4 Inconsistent variable naming5 Unused code6 Inappropriate naming (eg delegate, parent)7 Complex nested operations 8 Mixed responsibilities (handling XML and DOM implementation separately) | t | f | t | parent)7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 1552 | 11269 | |
| 5676 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | long method, feature envy, long parameter list | t | t | t | feature envy, long parameter list | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5676 | 11770 | |
| 2272 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2272 | 13768 | |
| 2198 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | the bad smells are: long method | t | t | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2198 | 13492 | ||
| 1046 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | long method, blob | t | t | t | blob | 0 | 9456 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1046 | 9456 | |
| 2203 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 2203 | 13507 | ||
| 2072 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | long method | t | t | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 2072 | 13027 | ||
| 1962 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | long method | t | t | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1962 | 12586 | ||
| 2558 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2558 | 14834 | |
| 984 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate naming conventions for variables (e.g. "v", "l", "vd") 3. Feature envy (defining a variable in a different class) 4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)") 7. Lack of comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Inappropriate naming conventions for variables (eg "v", "l", "vd")3 Feature envy (defining a variable in a different class)4 Use of unintuitive data types (eg List, Set, VarSymbol) 5 Poor code readability and organization 6 Code duplication (eg "vdvartype = access(vdvartype)")7 Lack of comments and documentation | t | f | t | "l", "vd")3. Feature envy (defining a variable in a different class)4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)")7. Lack of comments and documentation. | 0 | 8875 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 984 | 8875 | |
| 1836 | YES I found bad smells The bad smells are: Long method, Inappropriate naming, Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method, Inappropriate naming, Duplicate code | t | f | t | Inappropriate naming, Duplicate code | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 1836 | 12140 | |
| 1063 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1063 | 9551 | ||
| 1010 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method | t | t | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1010 | 9270 | ||
| 970 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 970 | 8695 | ||
| 2633 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 2633 | 15109 | ||
| 1580 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method, data class | t | t | t | data class | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1580 | 11359 | |
| 3968 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | long method, blob | t | t | t | blob | 0 | 10409 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 3968 | 10409 | |
| 1737 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1737 | 11831 | |
| 2397 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method | t | t | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2397 | 14375 | ||
| 1042 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 1042 | 9438 | ||
| 4573 | { "message": "YES, I found bad smells", "bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | feature envy, long method | t | t | t | feature envy | 0 | 12153 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 1 | 4573 | 12153 | |
| 4111 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Data class (lack of encapsulation) 5. Spaghetti code (multiple levels of nesting) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Data class (lack of encapsulation)5 Spaghetti code (multiple levels of nesting) | t | f | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 4111 | 10827 | ||
| 2678 | YES, I found bad smells. the bad smells are: 1. Long method 2. Commented out code 3. Useless if statement 4. Duplicated code 5. Inconsistent naming convention (camelCase and lowercase) 6. Magic number (0 in the if statement) 7. Feature envy (mailToAddresses and mailHost variables are called multiple times) 8. Mixing of responsibilities (sending email and error handling in the same method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Commented out code3 Useless if statement4 Duplicated code5 Inconsistent naming convention (camelCase and lowercase)6 Magic number (0 in the if statement)7 Feature envy (mailToAddresses and mailHost variables are called multiple times)8 Mixing of responsibilities (sending email and error handling in the same method) | t | f | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2678 | 15253 | ||
| 3334 | YES I found bad smells,the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 3334 | 6247 | ||
| 1050 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1050 | 9476 | ||
| 2387 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14351 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2387 | 14351 | ||
| 2015 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1: long method | t | t | f | long method | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2015 | 12768 | |
| 2499 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | long method, data class | t | t | t | data class | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2499 | 14652 | |
| 960 | YES I found bad smells - Long method, Feature envy: the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 960 | 8567 | ||
| 1880 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12284 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 1880 | 12284 | |
| 5490 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5490 | 1877 |
| 782 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 782 | 7477 | ||
| 2670 | public class CodeChecker { YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2 Feature envy | t | f | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2670 | 15211 | ||
| 701 | in the Airavata Registry * * * * @param authenticationToken The token which is generated by Airavata API server * * @param gatewayId The gateway for which the new experiment should be associated with * * @param experiment Experiment Model * * @return The server-side generated experiment-model identifier * * @throws RegistryServiceException * */YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Useless comments, 5 Code duplication, 6 Exception swallowing | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | 0 | 6688 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 701 | 6688 | |
| 506 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 506 | 5141 | ||
| 1934 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method | t | f | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 1934 | 12462 | ||
| 973 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8773 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 973 | 8773 | ||
| 1882 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | long method | t | t | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 1882 | 12288 | ||
| 407 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | 1. long method | t | t | f | long method | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 407 | 4155 | |
| 3905 | the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2 Feature envy | f | f | t | 2. Feature envy | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 3905 | 10223 | |
| 2197 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 2197 | 13483 | ||
| 1030 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1030 | 9383 | |
| 1279 | The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy | f | f | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1279 | 10593 | ||
| 2463 | COMMENT Sheyi, this is not Java code. But I've still included my feedback below. YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 2463 | 14551 | ||
| 383 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | 1. long method | t | t | f | long method | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 383 | 3920 | |
| 1461 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 1461 | 11023 | |
| 1999 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 1999 | 12705 | ||
| 1272 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1272 | 10573 | ||
| 1528 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 1528 | 11199 | |
| 99 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method | t | t | t | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 99 | 1298 | ||
| 270 | {"response": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 2 | 270 | 2901 | |
| 1309 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1309 | 10679 | |
| 3964 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting 5. Lack of comments/documentation 6. Poor variable naming 7. Potential for NullPointerException 8. Inefficient use of if/else blocks 9. Code repetition 10. Inappropriate use of nested loops 11. Poor exception handling 12. Potential for logical errors 13. Inconsistent use of braces 14. Lack of abstraction 15. Poor separation of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting5 Lack of comments/documentation6 Poor variable naming7 Potential for NullPointerException8 Inefficient use of if/else blocks9 Code repetition | t | f | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 3964 | 10391 | ||
| 1027 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Lack of comments 4. Primitive obsession 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method 2 Duplicate code 3 Lack of comments 4 Primitive obsession 5 Feature envy | t | f | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1027 | 9370 | ||
| 466 | the bad smells are: 1. Long method 2. Feature envy 3. Conditional complexity (multiple nested if statements) 4. Inconsistent formatting and indentation 5. Unclear variable names 6. Lack of comments/documentation 7. Duplicate code (throwing the same exception for different conditions) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method2 Feature envy3 Conditional complexity (multiple nested if statements)4 Inconsistent formatting and indentation 5 Unclear variable names 6 Lack of comments/documentation 7 Duplicate code (throwing the same exception for different conditions) | f | f | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 466 | 4523 | ||
| 1623 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 2 | 1623 | 11490 | ||
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 261 | 2843 | |
| 982 | YES I found bad smells the bad smells are: 1. Long method 2. Commented out code (case DEFAULT) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method2 Commented out code (case DEFAULT) | t | f | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 982 | 8859 | ||
| 1042 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1042 | 9438 | ||
| 2841 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 2841 | 1663 | ||
| 2369 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method | t | t | t | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 2369 | 14303 | ||
| 2112 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 2112 | 13189 | |
| 351 | YES I found bad smells The bad smells are:1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 351 | 3600 | ||
| 5639 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | long method | t | t | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5639 | 10918 | ||
| 4111 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 4111 | 10827 | ||
| 757 | {"message":"YES I found bad smells","bad smells are":["1. Long Method","2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 757 | 7057 | |
| 1604 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1604 | 11442 | |
| 5012 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method | t | t | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 5012 | 13779 | ||
| 1613 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3. Magic numbers/strings (e.g. -1, "Connection error while authenticating user") 4. Hard coded values (e.g. Version.CURRENT) 5. Code duplication (setting the secure part of the message twice) 6. Inconsistent formatting and indentation 7. Lack of proper error handling and comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | Long method2 Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3 Magic numbers/strings (eg - | t | f | t | 0 | 11470 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 1613 | 11470 | ||
| 1031 | { "error": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1031 | 9386 | ||
| 882 | YES I found bad smells The bad smells are: 1. Long method 2. Long method (commented section discussing subtle differences) 3. Feature envy (the if statement checking the value) 4. Duplicate code (repeated code for handling null values) 5. Long parameter list 6. Long method (within the if statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method 2 Long method (commented section discussing subtle differences) 3 Feature envy (the if statement checking the value) 4 Duplicate code (repeated code for handling null values) 5 Long parameter list 6 Long method (within the if statement) | t | f | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 882 | 8025 | ||
| 5690 | YES I found bad smells the bad smells are: 1. Blob 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Blob2 Long method | t | f | t | 0 | 12064 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 1 | 5690 | 12064 | ||
| 1224 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1224 | 10343 | ||
| 829 | {"message":"YES I found bad smells","bad_smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | 1. long method | t | t | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 829 | 7728 | ||
| 2397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2397 | 14375 | ||
| 2065 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | 1. long method | t | t | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 2065 | 12987 | ||
| 590 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Non-descriptive variable names 6. Deprecated code 7. Code commented out and not removed 8. Code that needs to be fixed (marked by FIXME) 9. Mixing of concerns (semantic check and inheritance check) 10. Mixing of levels of abstraction (parsing per clause and adding attribute to ajAttributes) 11. Unused variables (aspectAttribute) 12. Lack of error handling (returning false without specific error message) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Non-descriptive variable names6 Deprecated code7 Code commented out and not removed8 Code that needs to be fixed (marked by FIXME)9 Mixing of concerns (semantic check and inheritance check) | t | f | t | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 590 | 5890 | ||
| 3903 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | 1. long method | t | t | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3903 | 10219 | ||
| 2475 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | long method, data class | t | t | t | data class | 0 | 14585 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 1 | 2475 | 14585 | |
| 2157 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent formatting 6. Poor naming conventions 7. Inadequate commenting 8. Inefficient use of conditional statements 9. Inefficient use of variables 10. Poor use of class hierarchy 11. Mixing of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Feature envy 3 Duplicate code 4 Magic numbers 5 Inconsistent formatting 6 Poor naming conventions 7 Inadequate commenting 8 Inefficient use of conditional statements 9 Inefficient use of variables | t | f | t | 0 | 13311 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 2157 | 13311 | ||
| 361 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 361 | 3699 | ||
| 2613 | {"result": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | 1. long method | t | t | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 2613 | 15043 | ||
| 429 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 429 | 4276 | ||
| 1727 | private boolean isDSAPublicKeyWithoutParams(PublicKey key) { if (key.getAlgorithm().equals("DSA")) { try { key.getEncoded(); return false; } catch (NullPointerException npe) { return true; YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2Feature envy | t | f | t | 0 | 11810 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 1727 | 11810 | ||
| 964 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Logging throughout the method 5. Throwable catch-all 6. Insufficient comments/documentation 7. Multiple nested levels of code 8. Debug flag usage 9. Non-descriptive variable names 10. Commented-out code 11. Unused/unnecessary imports 12. Dependency injection used only for testing purposes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method 2 Feature envy 3 Code duplication 4 Logging throughout the method 5 Throwable catch-all 6 Insufficient comments/documentation 7 Multiple nested levels of code 8 Debug flag usage 9 Non-descriptive variable names | t | f | t | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 964 | 8595 | ||
| 4765 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | 1. long method | t | t | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 4765 | 12825 | ||
| 1834 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12132 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 1834 | 12132 | ||
| 1287 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1287 | 10613 | ||
| 780 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method, blob | t | t | t | blob | 0 | 7455 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 780 | 7455 | |
| 1898 | YES found bad smells Amongst the bad smells found are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 1898 | 12351 | ||
| 281 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Use of magic numbers 5. Inconsistent formatting 6. Mixing of business logic and presentation (the use of LOGGER to output an error message) 7. Potential null pointer exception (if maxFiles is null) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | Long method2 Feature envy3 Primitive obsession4 Use of magic numbers5 Inconsistent formatting 6 Mixing of business logic and presentation (the use of LOGGER to output an error message) 7 Potential null pointer exception (if maxFiles is null) | t | f | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 2 | 281 | 3011 | ||
| 1006 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | 1. long method | t | t | t | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1006 | 9258 | ||
| 2053 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | \n1. long method | t | t | f | long method | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 1 | 2053 | 12903 | |
| 1437 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code (repetitive use of "if" and "else" statements) 3. Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method2 Duplicate code (repetitive use of "if" and "else" statements)3 Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | t | f | t | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1437 | 10965 | ||
| 869 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 869 | 7948 | ||
| 1796 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1796 | 11999 | ||
| 1140 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
long method | blob, long method | t | t | t | blob | 0 | 10089 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 1 | 1140 | 10089 | |
| 1796 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1796 | 11999 | ||
| 934 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 934 | 8390 | ||
| 507 | {"message":"YES I found bad smells","bad smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | 1. long method | t | t | f | long method | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 507 | 5156 | |
| 1635 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1635 | 11522 | ||
| 5638 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5638 | 10869 | ||
| 561 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 561 | 5662 | ||
| 2021 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 12790 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 2021 | 12790 | ||
| 1933 | YES I found bad smells the bad smells are: 1.Long method, 2. Feature envy, 3. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | Long method, 2 Feature envy, 3 Code duplication | t | f | t | 2. Feature envy, 3. Code duplication. | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 1933 | 12457 | |
| 2268 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2268 | 13747 | |
| 2127 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 2127 | 13223 | ||
| 1523 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long Method | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 1523 | 11179 | ||
| 1373 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, data class | t | t | t | data class | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 1373 | 10803 | |
| 1647 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1647 | 11563 | ||
| 1719 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 1719 | 11792 | ||
| 450 | YES, I found bad smells. The bad smells are: 1. Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings. 2. Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand. 3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain. 4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods. 5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about. 6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues. 7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug. 8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read. 9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings2 Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand3 Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain4 Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods5 Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about6 Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues7 Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug8 Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read9 Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain | t | f | t | . Magic literal - the "unchecked" in the @SuppressWarnings annotation, which makes it hard to read and understand.3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain.4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods.5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about.6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues.7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug.8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read.9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 450 | 4392 | |
| 342 | YES I found bad smells: 1. Long method 2. Feature envy 3. Data class violation 4. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class violation4 Primitive obsession | t | f | t | 0 | 3502 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 342 | 3502 | ||
| 295 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | 1. long method | t | t | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 295 | 3109 | ||
| 2138 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 2138 | 13259 |
| 2040 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Long parameter list 4. Conditional complexity 5. Feature envy 6. Primitive obsession 7. Magic numbers/constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method 2 Duplicate code 3 Long parameter list 4 Conditional complexity 5 Feature envy 6 Primitive obsession7 Magic numbers/constants | t | f | t | 0 | 12850 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2040 | 12850 | ||
| 5638 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5638 | 10869 |
| 609 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 609 | 6124 | ||
| 1719 | YES I found bad smells the bad smells are: 1. Long method 2. Complex implementation 3. Overly nested conditional statements 4. Lack of proper commenting/documentation 5. Feature envy (multiple lines of code that should be in a separate object or method) 6. Use of magic numbers 7. Lack of proper error handling 8. Unnecessary use of system calls/arrays 9. Inefficient use of loops/iterations 10. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method 2 Complex implementation 3 Overly nested conditional statements 4 Lack of proper commenting/documentation 5 Feature envy (multiple lines of code that should be in a separate object or method) 6 Use of magic numbers 7 Lack of proper error handling 8 Unnecessary use of system calls/arrays 9 Inefficient use of loops/iterations | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 1719 | 11792 | ||
| 2188 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13444 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 2188 | 13444 | |
| 589 | { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 589 | 5882 | ||
| 5407 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 15185 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 5407 | 15185 | |
| 3521 | { "input_code": "public class Example {\n private int a;\n private int b;\n \n public int calculateSum() {\n return a + b;\n }\n\n public void printValues() {\n System.out.println(\"Value a: \" + a);\n System.out.println(\"Value b: \" + b);\n }\n}", "detected_code_smells": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smellsthe bad smells are:1. long method | t | t | t | 0 | 7615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/contentassist/antlr/internal/InternalN4JSParser.java/#L181223-L181248 | 1 | 3521 | 7615 | ||
| 2540 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2540 | 14774 | |
| 1101 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9839 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1101 | 9839 | ||
| 1246 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1246 | 10421 | |
| 1117 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Nested loops 6. Long parameter list 7. Tight coupling 8. Non-descriptive variable naming 9. Redundant code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Duplicate code4 Complex conditional statements5 Nested loops6 Long parameter list7 Tight coupling8 Non-descriptive variable naming9 Redundant code | t | f | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1117 | 9955 | ||
| 462 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 462 | 4467 | ||
| 1050 | YES I found bad smells the bad smells are: 1.Long method 2.Long method 3.Unnecessary comments 4.Lack of proper indentation/formatting 5.Lack of proper variable naming 6.Feature envy 7.Magic numbers/strings used in code 8.Manually handling exceptions instead of using try-catch blocks 9.Accessing properties multiple times instead of storing them in a variable 10.Multiple nested if-else statements 11.Missing error handling for exceptions 12.Hard-coded class and method names instead of using reflection 13.Large number of method calls 14.Methods performing multiple actions instead of a single, specific task. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2Long method3Unnecessary comments4Lack of proper indentation/formatting5Lack of proper variable naming6Feature envy7Magic numbers/strings used in code8Manually handling exceptions instead of using try-catch blocks9Accessing properties multiple times instead of storing them in a variable | t | f | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1050 | 9476 | ||
| 1657 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 1657 | 11601 | ||
| 1063 | { "message": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" }, { "2": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | 1: long method, 2: data class | t | t | t | 2: data class | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1063 | 9551 | |
| 1732 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | 1 Long Method | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 1 | 1732 | 11821 | ||
| 653 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 653 | 6389 | ||
| 3795 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | 1. long method | t | t | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 3795 | 9593 | ||
| 4487 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 4487 | 11883 | ||
| 2573 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method | t | f | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 2573 | 14908 | ||
| 483 | YES I found bad smells the bad smells are: 1. Long method 2. Lack of abstraction/encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method2 Lack of abstraction/encapsulation | t | f | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 483 | 4713 | ||
| 643 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple if-else statements) 4. Inappropriate type (using String instead of a constant or boolean) 5. Inconsistent formatting (missing spaces before and after braces) 6. Poor naming of variables (sel, sql, buf) 7. Tight coupling (method is heavily reliant on external methods and objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code (multiple if-else statements)4 Inappropriate type (using String instead of a constant or boolean)5 Inconsistent formatting (missing spaces before and after braces)6 Poor naming of variables (sel, sql, buf)7 Tight coupling (method is heavily reliant on external methods and objects) | t | f | t | sql, buf)7. Tight coupling (method is heavily reliant on external methods and objects) | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 643 | 6354 | |
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 240 | 2628 | ||
| 48 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Repeated code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method, repeated code | t | t | t | repeated code | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 48 | 854 | |
| 1003 | Yes, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inappropriate naming convention (variable names) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy3 Inappropriate naming convention (variable names) | t | f | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1003 | 9230 | ||
| 1644 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1644 | 11558 | ||
| 1125 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method | t | f | t | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 1125 | 10003 | ||
| 4065 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | long method | t | t | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 4065 | 10729 | ||
| 1443 | YES, I found bad smells the bad smells are: 1. Long Method, 2. Duplicated Code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long Method, 2 Duplicated Code | t | f | t | 2. Duplicated Code | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 1443 | 10977 | |
| 1287 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1287 | 10613 | ||
| 999 | "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method, 2 Feature envy" | t | f | t | 2. Feature envy." | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 999 | 9162 | |
| 402 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 402 | 4103 | ||
| 5584 | YES I found bad smells the smells are: 1. Feature envy 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Feature envy2 Long method | t | f | t | 0 | 9276 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5584 | 9276 | ||
| 1660 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long Method | t | f | t | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1660 | 11609 | ||
| 1739 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Long Method | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 1739 | 11836 | ||
| 2527 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2527 | 14726 | ||
| 2221 | Yes I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 2221 | 13553 | ||
| 1861 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1861 | 12222 | ||
| 717 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, 10. Use of compound assignments for complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Use of try-with-resources blocks for unrelated classes, 5 Inconsistent indentation, 6 Lack of comments and explanatory code, 7 Lack of meaningful variable and method names, 8 Duplicate code in try-with-resources blocks, 9 Use of multiple nested try-catch blocks, | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 2 | 717 | 6826 | |
| 787 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method | t | t | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 787 | 7509 | ||
| 1660 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method2 Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues 3 Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent 4 Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging | t | f | t | indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1660 | 11609 | |
| 5193 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | 1. long method | t | t | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 5193 | 14519 | ||
| 2540 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2540 | 14774 | ||
| 1432 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method, 2Magic numbers, 3Duplicate code, 4Long parameter list, 5 Feature envy, 6 Poor variable naming | t | f | t | 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 1432 | 10956 | |
| 2040 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | long method, blob | t | t | t | blob | 0 | 12850 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 2040 | 12850 | |
| 1502 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | long method, data class | t | t | t | data class | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 1502 | 11135 | |
| 2395 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2395 | 14373 | |
| 1913 | { "response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 1913 | 12402 | |
| 5271 | * * YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5271 | 14741 | ||
| 36 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 1 | 36 | 754 | ||
| 1680 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 1680 | 11666 | ||
| 3903 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3903 | 10219 | ||
| 2072 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 2072 | 13027 | ||
| 4605 | {"response":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | long method | t | t | t | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 4605 | 12253 | ||
| 1038 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeated code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Repeated code3 Feature envy | t | f | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1038 | 9410 | ||
| 671 | { "output": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method, blob | t | t | t | blob | 0 | 6554 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 671 | 6554 | |
| 1058 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Use of temporary variables 5. Exception handling inside a loop 6. Use of constant strings instead of enums 7. Use of raw types in collections 8. Use of multiple try-catch blocks with similar code 9. Poor exception handling (only logging the exception) 10. Lack of comments or documentation for complex logic and data structures. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy3 Duplicated code4 Use of temporary variables5 Exception handling inside a loop6 Use of constant strings instead of enums7 Use of raw types in collections8 Use of multiple try-catch blocks with similar code9 Poor exception handling (only logging the exception) | t | f | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1058 | 9520 | ||
| 2105 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 2105 | 13169 | ||
| 1045 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1045 | 9454 | ||
| 689 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | 1. long method | t | t | t | 0 | 6635 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 689 | 6635 | ||
| 2105 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Feature envy2 Long method | t | f | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 2105 | 13169 | ||
| 61 | { "answer": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } |
long method | 1. long method | t | t | t | 0 | 1020 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L473-L485 | 1 | 61 | 1020 | ||
| 2532 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 2532 | 14744 | |
| 1552 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long Method | t | f | t | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 1 | 1552 | 11269 | ||
| 2307 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 2307 | 14085 | |
| 631 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 631 | 6291 | ||
| 5639 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5639 | 10918 | ||
| 1810 | YES, I found bad smells, the bad smells are: 1. Long method 2. Repetitive code for removing double underscores 3. Excessive use of nested loops 4. Feature envy (the method is performing operations that should be done by another object) 5. Magic numbers without explanatory comments 6. Poor naming conventions (i, usIndex) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Repetitive code for removing double underscores3 Excessive use of nested loops4 Feature envy (the method is performing operations that should be done by another object)5 Magic numbers without explanatory comments6 Poor naming conventions (i, usIndex) | t | f | t | usIndex) | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1810 | 12056 | |
| 468 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 468 | 4551 | ||
| 346 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3525 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 346 | 3525 | |
| 1394 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1394 | 10850 | ||
| 904 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy3 Duplicate code | t | f | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 904 | 8176 | ||
| 2078 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | long method | t | t | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 2078 | 13053 | ||
| 1677 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 1677 | 11648 | ||
| 216 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 216 | 2343 | |
| 1204 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 1204 | 10287 | |
| 1030 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method | t | t | t | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1030 | 9383 | ||
| 1298 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | long method, blob | t | t | t | blob | 0 | 10639 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 1298 | 10639 | |
| 635 | YES I found bad smells the bad smells are: Long method, Feature envy, long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method, Feature envy, long parameter list | t | f | t | Feature envy, long parameter list | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 635 | 6305 | |
| 1790 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Duplicate code | t | f | t | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 1790 | 11987 | ||
| 1008 | Yes I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method | t | f | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1008 | 9268 | ||
| 4676 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 4676 | 12504 | |
| 1045 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1045 | 9454 | ||
| 2272 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2272 | 13768 | ||
| 2545 | YES, I found bad smells The bad smells are: 1. Long method 2. Unnecessary use of boolean flags 3. Mixing of concerns (i.e. handling memory management and file writing in the same method) 4. Magic numbers (i.e. the use of the number 3 in the memory size check) 5. Inconsistent naming conventions (i.e. using both camel case and snake case) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Unnecessary use of boolean flags3 Mixing of concerns (ie handling memory management and file writing in the same method)4 Magic numbers (ie the use of the number 3 in the memory size check)5 Inconsistent naming conventions (ie using both camel case and snake case) | t | f | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 2545 | 14790 | ||
| 230 | { "response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 230 | 2513 | |
| 1147 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1147 | 10122 | ||
| 2149 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method | t | t | t | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 2149 | 13283 | ||
| 1543 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1543 | 11243 | ||
| 963 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | long method, data class | t | t | t | data class | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 963 | 8574 | |
| 5507 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5507 | 3711 | |
| 1898 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | \n1. long method | t | t | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 1898 | 12351 | ||
| 958 | { "message": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | the bad smells are: long method | t | t | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 958 | 8556 | ||
| 561 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 561 | 5662 | |
| 3381 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | 1. long method | t | t | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 3381 | 6543 | ||
| 717 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | long method, data class | t | t | t | data class | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 1 | 717 | 6826 | |
| 2369 | YES, I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 2369 | 14303 | |
| 1225 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 1225 | 10351 | |
| 2193 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2193 | 13477 | |
| 671 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 6554 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 671 | 6554 | ||
| 1547 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long Method | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 1547 | 11256 | ||
| 136 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method | t | t | t | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 1 | 136 | 1673 | ||
| 2822 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | 1. long method | t | t | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 2822 | 1499 | ||
| 2307 | YES I found bad smells the bad smells are: 1. long method 2. feature envy 3. inconsistent naming conventions 4. unnecessary comments 5. lack of proper documentation or comments 6. hard-coded values 7. unnecessary type casting 8. long variable names 9. nested loops 10. excessive use of if/else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method2 feature envy3 inconsistent naming conventions4 unnecessary comments5 lack of proper documentation or comments6 hard-coded values7 unnecessary type casting8 long variable names9 nested loops | t | f | t | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 2307 | 14085 | ||
| 1555 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long Method | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 1555 | 11276 | ||
| 722 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Message chain 4. Duplicated code 5. Primitive obsession 6. Lazy class 7. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy3 Message chain4 Duplicated code 5 Primitive obsession6 Lazy class7 Shotgun surgery | t | f | t | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 722 | 6833 | ||
| 1043 | YES I found bad smells the bad smells are: Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | t | f | t | Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1043 | 9446 | |
| 1882 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 1882 | 12288 | ||
| 379 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | 1. long method | t | t | f | long method | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 379 | 3905 | |
| 592 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | blob, long method | t | t | t | blob | 0 | 5902 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 592 | 5902 | |
| 2048 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Use of nested maps and loops, which can make the code difficult to read and maintain 4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component 5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality. 6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java. 7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy3 Use of nested maps and loops, which can make the code difficult to read and maintain4 Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5 Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality6 Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java7 Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers | t | f | t | which can make the code difficult to read and maintain4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality.6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java.7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | 0 | 12878 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 2048 | 12878 | |
| 1745 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number (n > 0, index < n-1, index > 0) 3. Feature envy (container.getLength(), container.indexOf()) 4. Duplicated code (similar code blocks for FORWARD and BACKWARD cases) 5. Switch statement without a default case 6. Poor exception handling (throwing IllegalArgumentException instead of specific exceptions, ignoring other possible exceptions) 7. Lack of comments/documentation to explain the purpose of the method and its parameters/return value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method 2 Magic number (n > 0, index < n- | t | f | t | index < n- | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 1745 | 11851 | |
| 674 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 674 | 6568 | |
| 3940 | YES I found bad smells the bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 3940 | 10313 | ||
| 1970 | { "output": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1970 | 12607 | |
| 5709 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12658 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5709 | 12658 | |
| 2523 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method, data class | t | t | t | data class | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 2523 | 14713 | |
| 2003 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2003 | 12716 | |
| 1985 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | 1. long method | t | t | t | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 1985 | 12651 | ||
| 1008 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1008 | 9268 | ||
| 2666 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method | t | t | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 2666 | 15203 | ||
| 1847 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12172 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 1847 | 12172 | ||
| 5649 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | \n1. long method\n2. feature envy | t | t | f | long method | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 2 | 5649 | 11206 | |
| 1860 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 1860 | 12221 | ||
| 502 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicated code 4. Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method. 5. Use of hardcoded values instead of constants or variables 6. Multiple return statements - can be simplified to one return statement outside of the switch statement 7. Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Switch statement3 Duplicated code4 Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method 5 Use of hardcoded values instead of constants or variables6 Multiple return statements - can be simplified to one return statement outside of the switch statement7 Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks 8 Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting | t | f | t | specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 502 | 5087 | |
| 1132 | YES I found bad smells. the bad smells are: 1. Long method, 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | Long method, 2 Repetitive code, 3 Feature envy, 4 Poor variable naming, 5 Poor use of static methods | t | f | t | 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 2 | 1132 | 10040 | |
| 347 | {"message": "YES, I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | blob, long method | t | t | f | blob | long method | 0 | 3549 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 347 | 3549 |
| 1635 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1635 | 11522 | |
| 448 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | long method | t | t | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 448 | 4366 | ||
| 4044 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method, data class | t | t | t | data class | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 4044 | 10690 | |
| 5713 | Yes, I found bad smells. The bad smells are: 1. Long method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, 2Feature Envy | t | f | t | 2.Feature Envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5713 | 12782 | |
| 757 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 757 | 7057 | |
| 1572 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11341 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1572 | 11341 | |
| 2217 | {"message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method, data class | t | t | t | data class | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 2217 | 13539 | |
| 1152 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1152 | 10133 | |
| 752 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 752 | 7035 | |
| 2573 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 2573 | 14908 | ||
| 2535 | YES I found bad smells the bad smells are: 1.Long method, 2.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | Long method, 2Conditional complexity | t | f | t | 2.Conditional complexity | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 2535 | 14753 | |
| 1379 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 10817 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 1379 | 10817 | ||
| 2520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 2520 | 14709 | ||
| 2297 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 2297 | 14024 | ||
| 1345 | YES, I found bad smells the bad smells are: 1.Long method, 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method, 2Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind This code is tightly coupled 3Magic numbers: Type IDs like testITgetTypeID() make the code less readable | t | f | t | 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1345 | 10747 | |
| 1269 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | long method | t | t | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1269 | 10565 | ||
| 885 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 885 | 8053 | |
| 2426 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method, 2Magic numbers, 3Nested conditionals, 4Method chain, 5Inappropriate naming, 6Duplicated code, 7Complexity, 8Poor exception handling | t | f | t | 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 2426 | 14445 | |
| 1734 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1734 | 11823 | ||
| 1322 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1322 | 10699 | ||
| 2078 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 2078 | 13053 | ||
| 1227 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1227 | 10353 | ||
| 1997 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1997 | 12700 | ||
| 1972 | {"output": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | 1. long method | t | t | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 1 | 1972 | 12611 | ||
| 5481 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 1 | 5481 | 1263 | |
| 1840 | YES I found bad smells: 1. Long method, 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method, 2 Magic number, 3 Feature envy, 4 Duplicate code: LOGinfo statements, 5 Redundant code: null check for dirRoot, 6 Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7 Lack of clear separation of concerns: mixing of logging and crawling functionality, 8 Lack of proper error handling and exception handling | t | f | t | 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | 0 | 12149 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 1840 | 12149 | |
| 1172 | {"output": "YES I found bad smells\nthe bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1172 | 10197 | ||
| 959 | { "output": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 959 | 8560 | ||
| 374 | YES I found bad smells, the bad smells are: 1. Long method, 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Magic strings, 3 Multiple statements per line, 4 Duplicate code, 5 Non-descriptive variable names, 6 Hard-coded values, 7 Poorly structured code, 8 Feature envy | t | f | t | 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 374 | 3864 | |
| 1388 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1388 | 10839 | |
| 2523 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 2523 | 14713 | ||
| 1394 | YES I found bad smells. The detected bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1394 | 10850 | ||
| 2260 | YES, I found bad smells the bad smells are: 1. Commented out code 2. Multiple nested if-else statements 3. Use of instanceof operator 4. Use of a switch statement 5. Duplicate code 6. Naming conventions not followed (method name should be in lower camel case) 7. Inconsistent formatting/spacing 8. Long method (more than 10 lines of code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Commented out code2 Multiple nested if-else statements3 Use of instanceof operator4 Use of a switch statement5 Duplicate code6 Naming conventions not followed (method name should be in lower camel case)7 Inconsistent formatting/spacing8 Long method (more than | t | f | t | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 2260 | 13711 | ||
| 1502 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Complex conditional statements 6. Nested loops 7. Unnecessary try-catch blocks 8. Inadequate exception handling 9. Inconsistent indentation and formatting 10. Poor variable naming 11. Code comments that are unclear or obsolete 12. Lack of modularity and separation of concerns 13. Too many responsibilities for a single method 14. Use of outdated Java language features | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Code duplication4 Inconsistent naming conventions5 Complex conditional statements6 Nested loops7 Unnecessary try-catch blocks8 Inadequate exception handling9 Inconsistent indentation and formatting | t | f | t | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 1502 | 11135 | ||
| 1429 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10951 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1429 | 10951 | ||
| 961 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 961 | 8569 | ||
| 2185 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 13430 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 2185 | 13430 | |
| 1878 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 1878 | 12273 | ||
| 1647 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Inefficient looping 5. Inconsistent naming conventions 6. Lack of encapsulation/modularity 7. Inconsistent use of synchronized blocks 8. Complex conditional statements within loops 9. Use of break/continue statements 10. Lack of proper commenting/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Primitive obsession4 Inefficient looping5 Inconsistent naming conventions 6 Lack of encapsulation/modularity 7 Inconsistent use of synchronized blocks 8 Complex conditional statements within loops 9 Use of break/continue statements | t | f | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1647 | 11563 | ||
| 1179 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1179 | 10227 | ||
| 4086 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Switch statement with multiple cases 4. Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5. Multiple nested if statements 6. Use of input.LA() and input.index() methods multiple times 7. Use of input.rewind() method multiple times 8. Lack of proper naming conventions for variables and methods 9. Duplicate code within cases 1 and 2 10. Unclear and confusing method description and functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy3 Switch statement with multiple cases4 Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5 Multiple nested if statements 6 Use of inputLA() and inputindex() methods multiple times 7 Use of inputrewind() method multiple times 8 Lack of proper naming conventions for variables and methods 9 Duplicate code within cases | t | f | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 4086 | 10775 | ||
| 5777 | YES I found bad smells the bad smells are: 1. Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method | t | f | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5777 | 15213 | ||
| 755 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; } |
long method | blob, data class, long method | t | t | t | blob, data class | 0 | 7047 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 | 1 | 755 | 7047 | |
| 1817 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1817 | 12088 | |
| 1897 | "Yes, I found bad smells. The bad smells are: Feature envy, long method." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | Feature envy, long method" | t | f | t | Feature envy | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 1897 | 12341 | |
| 579 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method, data class | t | t | t | data class | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 579 | 5784 | |
| 1537 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11223 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 1537 | 11223 | ||
| 2203 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | long method, data class | t | t | t | data class | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 2203 | 13507 | |
| 1590 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 1590 | 11387 | ||
| 1322 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 1322 | 10699 | ||
| 4088 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | long method | t | t | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 4088 | 10777 | ||
| 5713 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5713 | 12782 | |
| 1923 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | long method | t | t | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1923 | 12426 | ||
| 1845 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2 Feature envy, 3 Indecent Exposure, 4 Drill-down, 5 Inappropriate Intimacy, 6 Temporary Field, 7 Large Class | t | f | t | 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 1845 | 12164 | |
| 1076 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Hard-coded string values 5. Nested looping 6. Duplicate code 7. Use of mutable data types without proper synchronization | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Commented out code4 Hard-coded string values5 Nested looping6 Duplicate code7 Use of mutable data types without proper synchronization | t | f | t | 0 | 9643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1076 | 9643 | ||
| 2042 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | 1. long method | t | t | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 2042 | 12854 | ||
| 119 | { "message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 119 | 1514 | |
| 4181 | YES I found bad smells. The bad smells are: 1. Long method 2. Magic number (the use of specific numbers without explanation) 3. Duplicate code (the repeated switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Magic number (the use of specific numbers without explanation)3 Duplicate code (the repeated switch statement) | t | f | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 4181 | 11002 | ||
| 2518 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14704 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 2518 | 14704 | |
| 1619 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1619 | 11477 | |
| 1580 | " YES I found bad smells" The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1580 | 11359 | |
| 4181 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | long method | t | t | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 4181 | 11002 | ||
| 4708 | YES I found bad smells the bad smells are: 1. Commented-out code 2. Long method 3. Complex conditional logic 4. Feature envy 5. Use of System.out.println() instead of using a logger 6. Magic numbers 7. Lack of proper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Commented-out code2 Long method3 Complex conditional logic4 Feature envy5 Use of Systemoutprintln() instead of using a logger6 Magic numbers7 Lack of proper exception handling | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 4708 | 12628 | ||
| 5193 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 5193 | 14519 | ||
| 637 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | long method | t | t | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 1 | 637 | 6316 | ||
| 2613 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 2613 | 15043 | ||
| 5744 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method | t | t | t | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5744 | 14137 | ||
| 2652 | return getCumulativeMemoryWithinPhase(join); YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2652 | 15177 | ||
| 1925 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (repeated try-catch block) 4. Conditional complexity (multiple if/else statements) 5. Inconsistent naming conventions (some variables use camel case, others use underscores) 6. Poor exception handling (all exceptions are caught and logged, but no further action is taken) 7. Magic numbers used for calculations (e.g. division by 100f) 8. Nested conditionals (if/else within another if/else) 9. Inefficient use of memory (converting integers to floats for calculations) 10. Comments indicating potential issues that need to be fixed (indicates unmaintainable code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy3 Duplicate code (repeated try-catch block)4 Conditional complexity (multiple if/else statements)5 Inconsistent naming conventions (some variables use camel case, others use underscores)6 Poor exception handling (all exceptions are caught and logged, but no further action is taken)7 Magic numbers used for calculations (eg division by | t | f | t | others use underscores)6. Poor exception handling (all exceptions are caught and logged, but no further action is taken)7. Magic numbers used for calculations (e.g. division by | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1925 | 12434 | |
| 722 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method, data class | t | t | t | data class | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 722 | 6833 | |
| 1687 | YES, I found bad smells: the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (specifically, the try/catch blocks for loading the comparator) 4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator) 5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException) 6. Use of multiple exit points (through the use of "throw" statements within the method) 7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes) 8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly) 9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) 10. Inadequate comments (lack of comments explaining the purpose and functionality of the code) 11. High cyclomatic complexity (multiple nested try/catch blocks and if statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long method 2 Feature envy3 Duplicate code (specifically, the try/catch blocks for loading the comparator)4 Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5 Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6 Use of multiple exit points (through the use of "throw" statements within the method)7 Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8 Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9 Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | t | f | t | the try/catch blocks for loading the comparator)4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6. Use of multiple exit points (through the use of "throw" statements within the method)7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 1687 | 11691 | |
| 900 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 900 | 8153 | ||
| 1200 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1200 | 10279 | |
| 1168 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | 1. long method | t | t | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1168 | 10191 | ||
| 2645 | YES I found bad smells! the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers (".class") 4. Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt") 5. Lack of proper documentation/commenting 6. Nested if statements and loops 7. Inconsistent formatting and spacing 8. Potential resource leak (input and output streams are not properly handled) 9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) 10. Poor variable and method naming 11. Lack of error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy3 Magic numbers ("class")4 Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt")5 Lack of proper documentation/commenting6 Nested if statements and loops7 Inconsistent formatting and spacing8 Potential resource leak (input and output streams are not properly handled)9 Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | t | f | t | "cr", "cw", "cv", "b", "os", "is", "f", "dt")5. Lack of proper documentation/commenting6. Nested if statements and loops7. Inconsistent formatting and spacing8. Potential resource leak (input and output streams are not properly handled)9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2645 | 15150 | |
| 791 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | long method | t | t | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 791 | 7535 | ||
| 224 | { "response": "YES, I found bad smells", "the bad smells are": [ "1. Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | 1. long method | t | t | t | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 2 | 224 | 2418 | ||
| 2156 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2156 | 13302 | ||
| 1962 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1962 | 12586 | ||
| 1957 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | blob, feature envy, long method | t | t | f | blob, feature envy | long method | 0 | 12568 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 1957 | 12568 |
| 963 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method 2 Feature Envy | t | f | t | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 963 | 8574 | ||
| 747 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | 1. long method | t | t | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 747 | 7016 | ||
| 1881 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | long method | t | t | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 1 | 1881 | 12286 | ||
| 2262 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 2262 | 13720 | ||
| 695 | YES, I found bad smells the bad smells are: 1.Long method 2. Feature envy 3. Repeating code 4. Code duplication 5. Insufficient commenting 6. Magic numbers 7. Primitive obsession 8. Inconsistent formatting 9. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method 2 Feature envy3 Repeating code4 Code duplication 5 Insufficient commenting 6 Magic numbers 7 Primitive obsession 8 Inconsistent formatting 9 Unused variables | t | f | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 695 | 6659 | ||
| 1985 | YES I found bad smells the bad smells are: 1. Duplicated code, 2. Feature envy, 3. Long method, 4. Lazy class, 5. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Duplicated code, 2 Feature envy, 3 Long method, 4 Lazy class, 5 Long parameter list | t | f | t | . Duplicated code, 2. Feature envy, 4. Lazy class, 5. Long parameter list | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 1985 | 12651 | |
| 2915 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | long method | t | t | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2915 | 2253 | ||
| 1538 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1538 | 11226 | ||
| 1636 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long Method | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 1636 | 11525 | ||
| 517 | "YES I found bad smells: Long method, Feature envy, Complex conditionals, Inconsistent name, Hardcoded numbers, "the bad smells are: 1. Long method 2. Feature envy 3. Complex conditionals 4. Inconsistent name 5. Hardcoded numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | Long method2 Feature envy3 Complex conditionals4 Inconsistent name5 Hardcoded numbers | t | f | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 2 | 517 | 5350 | ||
| 336 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 336 | 3447 | ||
| 2188 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 13444 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 2188 | 13444 | |
| 2164 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | long method | t | t | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 2164 | 13339 | ||
| 1106 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1106 | 9879 | ||
| 1278 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1278 | 10592 | ||
| 1435 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1435 | 10960 | ||
| 1891 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1891 | 12314 | ||
| 953 | {"message": "YES I found bad smells, the bad smells are:", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 953 | 8529 | ||
| 966 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 1 | 966 | 8633 | |
| 402 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | 1. long method | t | t | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 402 | 4103 | ||
| 2153 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 2153 | 13295 | ||
| 781 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 781 | 7457 | ||
| 2299 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Duplicate code 4. Hardcoded values 5. Unused variables 6. Poor exception handling 7. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Magic numbers3 Duplicate code4 Hardcoded values5 Unused variables6 Poor exception handling7 Excessive commenting | t | f | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 2299 | 14028 | ||
| 872 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | long method, data class | t | t | t | data class | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 1 | 872 | 7980 | |
| 2046 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | 1. long method | t | t | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 2046 | 12872 | ||
| 2326 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | 1. long method | t | t | t | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 2326 | 14143 | ||
| 1619 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1619 | 11477 | ||
| 1311 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method, data class | t | t | t | data class | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1311 | 10681 | |
| 1078 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1078 | 9647 | ||
| 2748 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | 1. long method | t | t | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2748 | 804 | ||
| 2422 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | 1. long method | t | t | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2422 | 14435 | ||
| 1058 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method | t | t | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1058 | 9520 | ||
| 1325 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1325 | 10702 | ||
| 3396 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 3396 | 6591 | ||
| 932 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 932 | 8357 | ||
| 2343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 2343 | 14182 | ||
| 2447 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | data class, long method | t | t | t | data class | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 2447 | 14497 | |
| 2583 | YES found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2583 | 14963 | ||
| 1397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1397 | 10854 | ||
| 1026 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1026 | 9361 | ||
| 230 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 230 | 2513 | |
| 2185 | YES I found bad smells the bad smells are: Long method, Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method,Duplicated code,Complex code,Feature envy,Inconsistent naming convention,Unnecessary comments | t | f | t | Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | 0 | 13430 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 2185 | 13430 | |
| 1103 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1103 | 9847 | ||
| 2504 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Feature Envy | t | f | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2504 | 14666 | ||
| 5325 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 14949 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 5325 | 14949 | ||
| 1142 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method | t | t | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1142 | 10095 | ||
| 934 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 934 | 8390 | ||
| 1419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10925 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1419 | 10925 | ||
| 1053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: next(), interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters 3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. 1 and 0) without any explanation or clear purpose, making it difficult to understand 6. Lack of comments: there are no comments in the code explaining the purpose or logic behind certain decisions or methods, making it difficult for future developers to understand 7. Poor naming conventions: variable names such as "next" and "method" are not descriptive enough, making it difficult to understand their purpose and usage | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method2 Feature envy: next(), interceptors, interceptorgetInstance(), interceptorgetMethod(), LifecycleInvocation, InterceptorInvocation, operationequals(), methodgetParameterTypes(), InvocationContextgetTimer(), BeanInvocation, target, method, methodParameters, parameters3 Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4 Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5 Magic numbers: the code contains integer values (eg | t | f | t | interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 1053 | 9480 | |
| 1454 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, data class | t | t | t | data class | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 1454 | 11007 | |
| 2683 | */ YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 15269 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 2683 | 15269 | ||
| 1694 | YES I found bad smells, 1. Long method, 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, 2 Complex conditional logic with multiple nested if statements, 3 Feature envy (internalFuture is accessed multiple times within the get() method), 4 Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5 Mixing of different levels of abstraction (usage of both explicit TimeUnitMILLISECONDS and direct system millisecond calculations) | t | f | t | 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1694 | 11718 | |
| 1168 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | Long method | t | f | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1168 | 10191 | ||
| 960 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | 1. long method | t | t | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 960 | 8567 | ||
| 2381 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2381 | 14338 | ||
| 3987 | YES I found bad smells the bad smells are: 1. Long method 2. Unnecessary use of try-catch-finally block for exception handling 3. Use of generic exceptions instead of specific ones 4. Lack of modularization or abstraction in the code 5. Use of primitive data types instead of classes for handling requests and responses 6. Inconsistent use of method parameters (e.g. handler vs. requests) 7. Mixing of different responsibilities within the method (e.g. transaction handling, error handling, request processing) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
long method | Long method2 Unnecessary use of try-catch-finally block for exception handling3 Use of generic exceptions instead of specific ones4 Lack of modularization or abstraction in the code5 Use of primitive data types instead of classes for handling requests and responses6 Inconsistent use of method parameters (eg handler vs requests)7 Mixing of different responsibilities within the method (eg transaction handling, error handling, request processing) | t | f | t | error handling, request processing) | 0 | 10502 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 3987 | 10502 | |
| 745 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 745 | 7007 | |
| 1747 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long Method | t | f | t | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1747 | 11855 | ||
| 507 | YES I found bad smells The bad smells are: 1.Long method 2.Magic strings 3.Coupled design 4.Incomplete error handling 5.Condition redundancy 6.Poorly named variable and method names 7.Inadequate commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method2Magic strings3Coupled design4Incomplete error handling5Condition redundancy6Poorly named variable and method names7Inadequate commenting/documentation | t | f | t | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 507 | 5156 | ||
| 2274 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 2274 | 13771 | |
| 86 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 86 | 1216 | |
| 1076 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | blob, long method | t | t | t | blob | 0 | 9643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 1076 | 9643 | |
| 1246 | YES I found bad smells. the bad smells are: 1.Long method 3.Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method3Magic numbers | t | f | t | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1246 | 10421 | ||
| 1000 | YES, I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 9174 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1000 | 9174 | ||
| 5507 | The bad smells are: 1.Long Method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method, 2Feature Envy | f | f | t | 2.Feature Envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5507 | 3711 | |
| 2404 | {"response": "YES I found bad smells the bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method | t | t | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 2404 | 14385 | ||
| 1053 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 1053 | 9480 | ||
| 2558 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2558 | 14834 | |
| 996 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 996 | 9119 | |
| 2901 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality. 3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case. 4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods. 5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality3 Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case4 Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods5 Large class - The class may have too many responsibilities and could be split into smaller, more focused classes | t | f | t | indicating that it may not be the best class to handle this functionality.3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case.4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods.5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 2901 | 2195 | |
| 1688 | { "YES I found bad smells": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 1688 | 11692 | |
| 940 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | long method | t | t | t | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 940 | 8460 | ||
| 3396 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1. long method | t | t | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 3396 | 6591 | ||
| 2197 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | long method | t | t | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 2197 | 13483 | ||
| 1926 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1926 | 12438 | ||
| 1441 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 1441 | 10974 | ||
| 318 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 2 | 318 | 3262 | ||
| 935 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 935 | 8393 | ||
| 484 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | long method | t | t | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 484 | 4743 | ||
| 5166 | :Parse the thrift exception and identify if exception belongs to workspace project or else Args: isAiravataException (bool) An object handle Returns: string YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Duplicated code2 Long method3 Feature envy | t | f | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5166 | 14457 | ||
| 3806 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery 5. Duplicate code 6. Inconsistent formatting 7. Poor naming conventions 8. Magic numbers 9. Hard-coded values 10. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Data class4 Shotgun surgery5 Duplicate code6 Inconsistent formatting7 Poor naming conventions8 Magic numbers9 Hard-coded values | t | f | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3806 | 9657 | ||
| 1430 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Lack of cohesion 5. Poor exception handling 6. Nested try-catch blocks 7. Inappropriate use of if-else statements 8. Poor naming conventions (e.g. methodName, meth) 9. Too many parameters in method's signature 10. Coupled code (e.g. accessing methods and fields from other classes without proper encapsulation) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy3 Duplicate code4 Lack of cohesion5 Poor exception handling6 Nested try-catch blocks7 Inappropriate use of if-else statements8 Poor naming conventions (eg methodName, meth)9 Too many parameters in method's signature | t | f | t | meth)9. Too many parameters in method's signature | 0 | 10952 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 1430 | 10952 | |
| 1830 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 1830 | 12121 | ||
| 1654 | YES I found bad smells the bad smells are: 1. Feature envy, 2. Long method, 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Feature envy, 2 Long method, 3 Duplicate code | t | f | t | . Feature envy, 3. Duplicate code | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 1654 | 11585 | |
| 2673 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2673 | 15225 | ||
| 2304 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting/layout 5. Magic numbers/constants 6. Non-descriptive variable names 7. Use of multiple nested if-else statements 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting/layout5 Magic numbers/constants6 Non-descriptive variable names7 Use of multiple nested if-else statements8 Lack of comments/documentation | t | f | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 2304 | 14061 | ||
| 1311 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1311 | 10681 | ||
| 5561 | { "output": "YES I found bad smells", "bad smells are": "1.Long method, 2.Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | 1.long method, 2.feature envy | t | t | f | 2.feature envy | long method | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 2 | 5561 | 7769 |
| 281 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | long method | t | t | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 1 | 281 | 3011 | ||
| 2683 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | long method, blob | t | t | t | blob | 0 | 15269 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 2683 | 15269 | |
| 1428 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 1428 | 10949 | ||
| 609 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 609 | 6124 | ||
| 1644 | YES I found bad smells The bad smells are: 1. Long method 2. Magic numbers 3. Complex conditionals 4. Feature envy 5. Large switch statement 6. Hard-coded values 7. Bad exception handling 8. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Magic numbers3 Complex conditionals4 Feature envy5 Large switch statement6 Hard-coded values7 Bad exception handling8 Code duplication | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1644 | 11558 | ||
| 1004 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1004 | 9254 | ||
| 2504 | { "answer": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2504 | 14666 | ||
| 1837 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code. 3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers. 4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code. 5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method. 6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring. 7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication. 8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand. 9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long method2 Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code3 Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers4 Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code5 Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method6 Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring7 Code duplication: some lines of code, such as "chldResgetResultColumns()", are duplicated in different parts of the code, indicating code duplication8 Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand9 Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation | t | f | t | including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code.3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers.4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code.5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method.6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring.7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication.8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand.9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 1837 | 12142 | |
| 1207 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | data class, long method | t | t | t | data class | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 1207 | 10290 | |
| 971 | { "output": "YES I found bad smells\nthe bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 971 | 8713 | ||
| 471 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 471 | 4568 | ||
| 1188 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 1188 | 10247 | |
| 3840 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | long method | t | t | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 3840 | 9895 | ||
| 2104 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | bad_smell: long method | t | t | f | long method | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 2104 | 13168 | |
| 1942 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1942 | 12499 | ||
| 2006 | {"response":"YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | 1. long method | t | t | f | long method | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 2006 | 12721 | |
| 2037 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method | t | t | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 2037 | 12838 | ||
| 491 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | 1. long method | t | t | f | long method | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 491 | 4899 | |
| 336 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Inconsistent Indentation 5. Primitive Obsession 6. Magic Numbers 7. Bloated code with unnecessary if-else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method 2 Feature Envy 3 Duplicate Code 4 Inconsistent Indentation 5 Primitive Obsession 6 Magic Numbers 7 Bloated code with unnecessary if-else statements | t | f | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 336 | 3447 | ||
| 197 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 197 | 2237 | ||
| 5722 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 12971 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 1 | 5722 | 12971 | ||
| 347 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method | t | f | t | 0 | 3549 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 347 | 3549 | ||
| 119 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method | t | t | t | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 119 | 1514 | ||
| 998 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 2 | 998 | 9158 | ||
| 2029 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Magic strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method, 2Magic numbers, 3Magic strings | t | f | t | 2.Magic numbers, 3.Magic strings | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 2029 | 12807 | |
| 449 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method | t | f | t | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 449 | 4369 | ||
| 5690 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 12064 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5690 | 12064 | |
| 3548 | { "input_code": "public class Example {\n private int x;\n private int y;\n\n public Example(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public int calculateSum() {\n return x + y;\n }\n}", "detected_bad_smells": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smells the bad smells are: 1. long method | t | t | t | 0 | 7729 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 3548 | 7729 | ||
| 2259 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 2259 | 13703 | |
| 606 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number (128 * 1024) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Magic number ( | t | f | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 606 | 6083 | ||
| 1636 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 1636 | 11525 | ||
| 709 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 709 | 6757 | ||
| 569 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method" }, { "2. Feature Envy": "Feature Envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | 1. long method: long method, 2. feature envy: feature envy | t | t | t | 2. feature envy: feature envy | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 569 | 5727 | |
| 1548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1548 | 11258 | |
| 1451 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1451 | 11000 | ||
| 1435 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1435 | 10960 | ||
| 998 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | long method | t | t | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 1 | 998 | 9158 | ||
| 1003 | {"response": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | 1. long method | t | t | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1003 | 9230 | ||
| 589 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 589 | 5882 | ||
| 1373 | YES I found bad smells, The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 1373 | 10803 | ||
| 637 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 2 | 637 | 6316 | ||
| 2376 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | long method | t | t | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 2376 | 14325 | ||
| 1956 | { "response": "YES, I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | long method | t | t | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 1 | 1956 | 12558 | ||
| 3479 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 3479 | 7119 | |
| 1459 | YES, I found bad smells the bad smells are: 1. Long method 2. Commented out code 3. Use of try-catch without any specific exception handling 4. Use of magic numbers/constant values 5. Feature envy (multiple methods making use of metrics from ClusterMetrics class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Commented out code3 Use of try-catch without any specific exception handling4 Use of magic numbers/constant values5 Feature envy (multiple methods making use of metrics from ClusterMetrics class) | t | f | t | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1459 | 11020 | ||
| 257 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | long method | t | t | t | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 1 | 257 | 2777 | ||
| 1787 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11981 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 1787 | 11981 | ||
| 1352 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1352 | 10761 | ||
| 2104 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | Long method | t | f | t | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 2104 | 13168 | ||
| 3912 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 3912 | 10243 | ||
| 173 | { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method, data class | t | t | t | data class | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 173 | 2041 | |
| 1420 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1420 | 10928 | |
| 1078 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | 1. long method | t | t | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1078 | 9647 | ||
| 5531 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5531 | 5816 | |
| 1682 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 1682 | 11682 | |
| 1278 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple if statements in a row 4. Hardcoded values for class types, which could lead to maintenance issues if types change in the future 5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy3 Multiple if statements in a row4 Hardcoded values for class types, which could lead to maintenance issues if types change in the future5 Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | t | f | t | which could lead to maintenance issues if types change in the future5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1278 | 10592 | |
| 4359 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method | t | t | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 4359 | 11504 | ||
| 287 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | 1. long method | t | t | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 287 | 3060 | ||
| 1345 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1345 | 10747 | |
| 1227 | YES I found bad smells the bad smells are: 1. Commented out code 2. Long method 3. Feature envy 4. Inconsistent indentation 5. Non-descriptive variable names 6. Nested if statements 7. Lack of error handling for exceptions 8. Multiple responsibilities in one method (parsing, handling exceptions, building results map) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Commented out code2 Long method3 Feature envy4 Inconsistent indentation5 Non-descriptive variable names6 Nested if statements7 Lack of error handling for exceptions8 Multiple responsibilities in one method (parsing, handling exceptions, building results map) | t | f | t | handling exceptions, building results map) | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1227 | 10353 | |
| 5676 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5676 | 11770 | ||
| 2117 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Comments 4. Magic numbers 5. Use of raw types | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Feature envy 2 Long method 3 Comments 4 Magic numbers 5 Use of raw types | t | f | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 2117 | 13197 | ||
| 1956 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 2 | 1956 | 12558 | ||
| 5773 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5773 | 14885 | ||
| 5535 | YES I found bad smells the bad smells are: Data class, Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Data class, Long method | t | f | t | Data class | 0 | 6189 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5535 | 6189 | |
| 1687 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method | t | f | t | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 1687 | 11691 | ||
| 4239 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 4239 | 11159 | ||
| 1785 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long Method | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 1785 | 11978 | ||
| 1737 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1737 | 11831 | |
| 762 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 762 | 7113 | |
| 318 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 318 | 3262 | ||
| 5759 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5759 | 14515 | ||
| 469 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1.": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | 1.: long method | t | t | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 469 | 4555 | ||
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method, data class | t | t | t | data class | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 261 | 2843 | |
| 495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 495 | 5014 | |
| 335 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method 2 Feature Envy | t | f | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 335 | 3439 | ||
| 3557 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7777 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 3557 | 7777 | ||
| 1931 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1931 | 12454 | ||
| 959 | YES, I found bad smells: 1. Long method 2. Feature envy 3. Data clumps 4. Primitive obsession 5. Inconsistent naming conventions 6. Duplicate code 7. Poor exception handling 8. Tight coupling 9. Multiple responsibilities 10. Lack of proper abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | Long method2 Feature envy3 Data clumps4 Primitive obsession5 Inconsistent naming conventions6 Duplicate code7 Poor exception handling8 Tight coupling9 Multiple responsibilities | t | f | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 959 | 8560 | ||
| 845 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 845 | 7823 | ||
| 4487 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 4487 | 11883 | |
| 2530 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | long method | t | t | t | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 1 | 2530 | 14736 | ||
| 5710 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5710 | 12666 | ||
| 2447 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Duplicate code3 Feature Envy | t | f | t | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 2447 | 14497 | ||
| 2699 | { "output": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 2699 | 15326 | |
| 445 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | the bad smells are: long method | t | t | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 1 | 445 | 4346 | ||
| 1747 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1747 | 11855 | |
| 1797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 1797 | 12001 | ||
| 1217 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1217 | 10323 | ||
| 781 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 781 | 7457 | |
| 48 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method | t | t | t | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 48 | 854 | ||
| 486 | { "message": "YES I found bad smells", "bad smells are:": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 486 | 4755 | |
| 953 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 953 | 8529 | ||
| 2342 | YES I found bad smells. The bad smells are:Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 2342 | 14179 | |
| 1826 | YES I found bad smells the bad smells are: 1.Long method 2.Magic number 3.Duplicate code 4.Message chains 5.Data class 6.Inappropriate intimacy 7.Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method 2Magic number 3Duplicate code 4Message chains 5Data class 6Inappropriate intimacy7Shotgun surgery | t | f | t | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 1826 | 12112 | ||
| 2376 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 2376 | 14325 | ||
| 1615 | YES I found bad smells The bad smells are: 1. Duplicate code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Duplicate code 2 Long method 3 Feature envy | t | f | t | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 1615 | 11472 | ||
| 2003 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Nested loops 4. Use of var instead of specific data types 5. Poor variable names 6. Feature envy 7. Use of deprecated code (such as FSUtils.getRootDir()) 8. Duplicate code (such as using LOG.isTraceEnabled() twice) 9. Use of "continue" statement 10. Complex conditionals (such as if(srcIdx < 0)) 11. Use of hard-coded values (such as Bytes.toBytes()) 12. Catching and throwing generic exceptions (such as IOException) instead of specific ones 13. Use of multiple return statements 14. Inconsistent indentations 15. Use of multiple assignments in one line 16. Use of "else" statements (can be refactored into guard clauses) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Magic numbers3 Nested loops4 Use of var instead of specific data types5 Poor variable names6 Feature envy7 Use of deprecated code (such as FSUtilsgetRootDir())8 Duplicate code (such as using LOGisTraceEnabled() twice)9 Use of "continue" statement | t | f | t | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2003 | 12716 | ||
| 2497 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, 10.Excessive comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2Magic numbers, 3Unnecessary variables, 4Poorly named variables, 5Inconsistent coding style, 6Possible null pointer exception, 7Duplicate code, 8Hard-coded values, 9No exception handling, | t | f | t | 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 2497 | 14646 | |
| 345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 345 | 3519 | ||
| 353 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2Magic numbers, 3Duplicated code, 4Nested try/catch blocks, 5Unused parameters, 6Inconsistent naming conventions, 7Hardcoded class names | t | f | t | 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 353 | 3634 | |
| 1768 | "YES I found bad smells Bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Long parameter list 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Repeated code3 Feature envy4 Long parameter list5 Primitive obsession | t | f | t | 0 | 11914 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1768 | 11914 | ||
| 1800 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Inconsistent indentations 4. Magic numbers 5. Nested if statements 6. Complex boolean expressions 7. Hard-to-understand variable names 8. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method 2 Duplicate code 3 Inconsistent indentations 4 Magic numbers 5 Nested if statements 6 Complex boolean expressions 7 Hard-to-understand variable names 8 Unused variables | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 1800 | 12011 | ||
| 471 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Switch statement 5. Magic numbers (e.g. 0, 1, 2) 6. Unused variable (_s) 7. Duplicate code within cases 8. Failed state tracking 9. Indentation issues 10. Unclear variable names and method names 11. Multiple return statements within cases | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Repeated code3 Feature envy4 Switch statement5 Magic numbers (eg 0, | t | f | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 471 | 4568 | ||
| 1892 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method, 2Magic Number, 3Duplicated code, 4Data clumps, 5Conditional complexity | t | f | t | 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 1892 | 12318 | |
| 783 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 783 | 7493 | ||
| 883 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 883 | 8029 | ||
| 35 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 35 | 743 | |
| 3964 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 3964 | 10391 | ||
| 756 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class, 3. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | 1. long method, 2. data class, 3. blob | t | t | t | 2. data class, 3. blob | 0 | 7049 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 1 | 756 | 7049 | |
| 3937 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 3937 | 10309 | ||
| 1343 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | 1. long method, 2. blob | t | t | t | 2. blob | 0 | 10745 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1343 | 10745 | |
| 2262 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Nested loops 6. Conditional complexity 7. Misleading variable names 8. Hard-coded strings 9. Bad indentation and formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Nested loops6 Conditional complexity7 Misleading variable names8 Hard-coded strings9 Bad indentation and formatting | t | f | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 2262 | 13720 | ||
| 4044 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 4044 | 10690 | ||
| 4205 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | long method | t | t | t | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 1 | 4205 | 11065 | ||
| 254 | { "message": "YES I found bad smells", "bad smells are": ["1.Long method"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1.long method | t | t | t | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 254 | 2738 | ||
| 1947 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 1947 | 12523 | ||
| 1239 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | long method, blob | t | t | t | blob | 0 | 10404 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 1239 | 10404 | |
| 829 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Use of magic numbers for reader state checks 4. Use of super keyword without clear purpose/reasoning 5. Inconsistent formatting and indentation 6. Complex logic and potential for errors with multiple return statements and conditional checks within the method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Switch statement3 Use of magic numbers for reader state checks4 Use of super keyword without clear purpose/reasoning5 Inconsistent formatting and indentation6 Complex logic and potential for errors with multiple return statements and conditional checks within the method | t | f | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 829 | 7728 | ||
| 2236 | { "answer": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
long method | 1. long method | t | t | t | 0 | 13611 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 2236 | 13611 | ||
| 1829 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 1829 | 12118 | |
| 2306 | YES I found bad smells" 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 2306 | 14069 | ||
| 1484 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method | t | f | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 1484 | 11088 | ||
| 491 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 491 | 4899 | ||
| 2221 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 2221 | 13553 | |
| 2699 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 2699 | 15326 | ||
| 1224 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1224 | 10343 | ||
| 2149 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 2149 | 13283 | |
| 1309 | YES I found bad smells the bad smells are: 1. Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell. 2. Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell2 Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell | t | f | t | . Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1309 | 10679 | |
| 1547 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase) 4. Magic numbers (numerical values assigned without explanation) 5. Use of ArrayList instead of List interface 6. Use of comment block instead of proper documentation 7. Overloaded constructor with multiple arguments 8. Boolean flag parameters in addAttribute() method 9. Large number of parameters in addElement() and addAttribute() methods 10. Hard-coded values instead of using constants or variables 11. Unused variables/reserved word "res" 12. Poorly named variables (e.g. "cod | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase)4 Magic numbers (numerical values assigned without explanation)5 Use of ArrayList instead of List interface6 Use of comment block instead of proper documentation 7 Overloaded constructor with multiple arguments 8 Boolean flag parameters in addAttribute() method 9 Large number of parameters in addElement() and addAttribute() methods | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 1547 | 11256 | ||
| 632 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | long method | t | t | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 632 | 6293 | ||
| 36 |
{ "response": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 2 | 36 | 754 | ||
| 631 | { "output": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 1 | 631 | 6291 | |
| 5648 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11201 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5648 | 11201 | |
| 635 | { "message": "YES I found bad smells", "detected_bad_smells": "The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 635 | 6305 | ||
| 3794 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 9585 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 3794 | 9585 | |
| 2901 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 2901 | 2195 | |
| 756 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7049 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 2 | 756 | 7049 | |
| 2368 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | long method, data class | t | t | t | data class | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 2368 | 14301 | |
| 1763 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long Method | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 1763 | 11896 | ||
| 1027 | {"message": "YES I found bad smells", "bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method | t | t | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1027 | 9370 | ||
| 3589 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | long method, data class | t | t | t | data class | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 1 | 3589 | 7923 | |
| 3589 | the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Long method2 Feature envy | f | f | t | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 3589 | 7923 | ||
| 924 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8307 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 924 | 8307 | |
| 2115 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 2115 | 13193 | ||
| 1588 | YES I found bad smells The bad smells are: 1.Method with multiple responsibilities 2. Complex conditional logic 3. Long method 4. Feature envy 5. Duplicate code 6. Dependency on specific implementation 7. Dependency on specific feature | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Method with multiple responsibilities2 Complex conditional logic3 Long method4 Feature envy5 Duplicate code6 Dependency on specific implementation7 Dependency on specific feature | t | f | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 1588 | 11376 | ||
| 932 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Long parameter list 4. Duplicate code 5. Comments that explain bad code 6. Nested conditionals 7. Inappropriate level of abstraction 8. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Long method2 Feature envy3 Long parameter list4 Duplicate code5 Comments that explain bad code 6 Nested conditionals7 Inappropriate level of abstraction8 Inconsistent naming conventions | t | f | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 932 | 8357 | ||
| 2302 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, data class | t | t | t | data class | 0 | 14043 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 2302 | 14043 | |
| 695 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | 1. long method | t | t | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 695 | 6659 | ||
| 2050 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | long method | t | t | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 1 | 2050 | 12885 | ||
| 1665 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1665 | 11622 | ||
| 2548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | long method, data class | t | t | t | data class | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 2548 | 14793 | |
| 2153 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Mix of responsibilities (method is responsible for too many things) 4. Inconsistent formatting and naming conventions 5. Arbitrary integer value used without clear explanation or justification 6. Nested if statements 7. Use of null values 8. Use of raw data types instead of object-oriented approach 9. Potential for null pointer exception 10. Potential for index out of bounds exception 11. Magic numbers/strings used (e.g. 0, "0") 12. Violation of the Single Responsibility Principle (SRP) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method2 Duplicate code3 Mix of responsibilities (method is responsible for too many things)4 Inconsistent formatting and naming conventions5 Arbitrary integer value used without clear explanation or justification6 Nested if statements7 Use of null values8 Use of raw data types instead of object-oriented approach9 Potential for null pointer exception | t | f | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 2153 | 13295 | ||
| 5781 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5781 | 15317 | ||
| 2450 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2450 | 14505 | |
| 1388 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, 10. Hard-coded values/strings, 11. Use of deprecated methods, 12. Lack of abstraction/separation of concerns, 13. Potential NullPointerExceptions, 14. Unused variables, 15. Lack of error handling/reporting, 16. Inadequate naming of variables/methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Nested conditionals, 6 Large number of parameters, 7 Lack of comments/documentation, 8 High complexity/low readability, 9 Inconsistent formatting, | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1388 | 10839 | |
| 2298 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | long method, data class | t | t | t | data class | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 2298 | 14025 | |
| 1785 | YES I found bad smells: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 1785 | 11978 | ||
| 1432 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method, data class | t | t | t | data class | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 1432 | 10956 | |
| 1520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1520 | 11172 | ||
| 2046 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers/strings 3. Feature envy 4. Testing multiple scenarios within a single test method 5. Lack of proper comments/documentation 6. Lack of clear and concise variable names 7. Unnecessary/redundant code (e.g. using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers/strings3 Feature envy4 Testing multiple scenarios within a single test method5 Lack of proper comments/documentation6 Lack of clear and concise variable names7 Unnecessary/redundant code (eg using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | t | f | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 2046 | 12872 | ||
| 484 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method2 Feature envy | t | f | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 484 | 4743 | ||
| 1603 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1603 | 11438 | ||
| 1190 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1190 | 10253 | ||
| 1031 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Useless comments (ex: "@Override @MultiMQAdminCmdMethod") 4. Use of multiple catch statements for different exceptions 5. Nested for loops and try-catch statements 6. Repeated code (ex: calling mqAdminExt.resetOffsetByTimestamp twice) 7. Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList) 8. Lack of encapsulation/abstraction (ex: direct access to class attributes) 9. Use of Maps and Lists instead of more object-oriented data structures 10. Nested if-else statements 11. Use of continue statement to skip code (ex: "continue;" in the catch block) 12. Lack of exception handling techniques like throwing/catching custom exceptions 13. Lack of separation of concerns (resetOffset method has multiple responsibilities) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy3 Useless comments (ex: "@Override @MultiMQAdminCmdMethod")4 Use of multiple catch statements for different exceptions5 Nested for loops and try-catch statements6 Repeated code (ex: calling mqAdminExtresetOffsetByTimestamp twice)7 Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList)8 Lack of encapsulation/abstraction (ex: direct access to class attributes)9 Use of Maps and Lists instead of more object-oriented data structures | t | f | t | rollbackStats, rollbackStatsMap, rollbackStatsList)8. Lack of encapsulation/abstraction (ex: direct access to class attributes)9. Use of Maps and Lists instead of more object-oriented data structures | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1031 | 9386 | |
| 1033 | YES I found bad smells The bad smells are: 1. Long method 2. Exception throwing (multiple exceptions in method signature) 3. Dependency on specific library (java.util.concurrent) 4. Inconsistent variable naming conventions 5. Multiple nested if statements 6. Lack of comments or documentation explaining the purpose of the method and its parameters 7. Possible synchronization issues (using wait() without a corresponding notify() or notifyAll()) 8. Code duplication (using the same code to check for internalFuture and to calculate remaining time) 9. Hard to read and understand code flow due to excessive use of ternary operator (? and :) 10. Magic numbers (1, TimeUnit.MILLISECONDS) used without explanation or context. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method2 Exception throwing (multiple exceptions in method signature)3 Dependency on specific library (javautilconcurrent)4 Inconsistent variable naming conventions5 Multiple nested if statements6 Lack of comments or documentation explaining the purpose of the method and its parameters7 Possible synchronization issues (using wait() without a corresponding notify() or notifyAll())8 Code duplication (using the same code to check for internalFuture and to calculate remaining time)9 Hard to read and understand code flow due to excessive use of ternary operator (? and :) | t | f | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1033 | 9391 | ||
| 2597 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 2597 | 15009 | ||
| 693 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 693 | 6654 | |
| 1842 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 1842 | 12151 | ||
| 1217 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent formatting 5. Poor naming conventions (e.g. "sql", "sel", "params") 6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks) 7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()") 8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause") 9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) 10. Lack of comments and documentation on the purpose and logic of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code4 Inconsistent formatting5 Poor naming conventions (eg "sql", "sel", "params")6 Possible code duplication (eg in the "if (updateParams == null)" and "else" blocks)7 Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8 Possible excessive use of boolean flags (eg "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9 Possible violation of SOLID principles (eg Single Responsibility, Open/Closed) | t | f | t | "sel", "params")6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks)7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1217 | 10323 | |
| 461 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 2 | 461 | 4463 | ||
| 2426 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 2426 | 14445 | ||
| 1603 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long Method | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1603 | 11438 | ||
| 3479 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 3479 | 7119 | ||
| 2670 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2670 | 15211 | ||
| 598 | {"response": "YES I found bad smells. The bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | 1. long method | t | t | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 598 | 5982 | ||
| 394 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 394 | 3978 | ||
| 1305 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 1305 | 10673 | |
| 5771 | YES, I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 14811 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5771 | 14811 | ||
| 5781 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5781 | 15317 | ||
| 1440 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method | t | t | t | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 1440 | 10972 | ||
| 908 | { "answer": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | blob, long method | t | t | t | blob | 0 | 8202 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 908 | 8202 | |
| 1875 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1875 | 12262 | |
| 592 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5902 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 592 | 5902 | ||
| 1829 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 1829 | 12118 | ||
| 995 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9092 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 995 | 9092 | |
| 997 | {"message":"YES I found bad smells","bad_smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method | t | t | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 997 | 9139 | ||
| 2822 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 2822 | 1499 | ||
| 1657 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 1657 | 11601 | |
| 1934 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 1934 | 12462 | ||
| 1933 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method | t | t | t | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 1933 | 12457 | ||
| 2306 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | 1. long method | t | t | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 2306 | 14069 | ||
| 861 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are: 1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 861 | 7903 | ||
| 5691 | YES I found bad smells The bad smells are: 1. Blob, 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Blob, 2 Long method | t | f | t | . Blob | 0 | 12087 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5691 | 12087 | |
| 371 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 371 | 3852 | ||
| 2326 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 2326 | 14143 | |
| 2297 | YES, I found bad smells: 1. Long method 2. Complex code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Complex code | t | f | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 2297 | 14024 | ||
| 513 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 513 | 5219 | ||
| 999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | long method | t | t | t | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 999 | 9162 | ||
| 449 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 449 | 4369 | |
| 1710 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 1710 | 11765 | |
| 1682 | return HiveAlgorithmsUtil.getJoinCumulativeMemoryWithinPhaseSplit(join); YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 1682 | 11682 | ||
| 1190 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1190 | 10253 | |
| 804 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 804 | 7620 | |
| 1997 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1997 | 12700 | ||
| 2029 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 2029 | 12807 | ||
| 1789 | YES, I found bad smells. The bad smells are: 1. Long method 2. Unnecessary complexity 3. Feature envy 4. Code duplication 5. Inappropriate coupling 6. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long method2 Unnecessary complexity3 Feature envy4 Code duplication5 Inappropriate coupling6 Incomplete error handling | t | f | t | 0 | 11985 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 1789 | 11985 | ||
| 2582 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 2582 | 14956 | |
| 1885 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, blob | t | t | t | blob | 0 | 12293 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 1885 | 12293 | |
| 5498 | YES I found bad smells. The bad smells are: Long method. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
long method | Long method | t | f | t | 0 | 3000 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5498 | 3000 | ||
| 5407 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | blob, long method | t | t | t | blob | 0 | 15185 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 5407 | 15185 | |
| 575 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplication of code 5. Inconsistent formatting and naming conventions 6. Violation of the single responsibility principle 7. Use of complex structures and data types in parameters 8. Inefficient use of variables and data structures 9. Inadequate error handling and input validation 10. Use of hard-coded or external resources without proper abstraction. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy3 Magic numbers4 Duplication of code5 Inconsistent formatting and naming conventions6 Violation of the single responsibility principle7 Use of complex structures and data types in parameters8 Inefficient use of variables and data structures9 Inadequate error handling and input validation | t | f | t | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 575 | 5777 | ||
| 1272 | {"result": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1272 | 10573 | |
| 2583 | { "message": "YES I found bad smells", "the bad smells are": [ "3. Feature Envy", "4. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | 3. feature envy, 4. long method | t | t | t | 3. feature envy | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2583 | 14963 | |
| 2062 | YES, I found bad smells 1. Conditional complexity 2. Duplicate code 3. Long method 4. Long parameter list 5. Primitive obsession 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Conditional complexity2 Duplicate code 3 Long method 4 Long parameter list 5 Primitive obsession 6 Feature envy | t | f | t | 0 | 12975 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 2062 | 12975 | ||
| 1279 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1279 | 10593 | ||
| 3694 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 3694 | 8659 | ||
| 2748 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Poor exception handling 4. Use of magic numbers 5. Lack of proper commenting/documentation 6. Unnecessary nesting in switch statement 7. Unnecessary use of mutable fields 8. Potential for memory leaks through use of mutable fields without proper resetting before return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy3 Poor exception handling4 Use of magic numbers5 Lack of proper commenting/documentation6 Unnecessary nesting in switch statement7 Unnecessary use of mutable fields 8 Potential for memory leaks through use of mutable fields without proper resetting before return statements | t | f | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2748 | 804 | ||
| 1651 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 1651 | 11579 | ||
| 1490 | YES I found bad smells the bad smells: 1.Split temporary variable, 2.Long method, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, 10.Duplicate code, 11.Functional decomposition, 12.Long parameter list. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Split temporary variable, 2Long method, 3Feature envy, 4Primitive obsession, 5Magic numbers, 6Inappropriate intimacy, 7Unnecessary temporary variables, 8Speculative generality, 9Nested loops, | t | f | t | .Split temporary variable, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1490 | 11110 | |
| 2340 | YES, bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 2340 | 14174 | ||
| 3905 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | 1. long method | t | t | t | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 3905 | 10223 | ||
| 2527 | YES, I found bad smells the bad smells are: 1. Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand. 2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand2 Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method | t | f | t | making it difficult to read and understand.2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2527 | 14726 | |
| 1451 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1451 | 11000 | ||
| 5401 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | blob, long method | t | t | t | blob | 0 | 15176 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 5401 | 15176 | |
| 2168 | YES I found bad smells The bad smells are: 1. Long method 2. Redundant code 3. Feature envy 4. Comments to state the obvious 5. Magic numbers 6. Inconsistent naming conventions 7. Inconsistent formatting 8. Poor exception handling 9. Code duplication with slight variations | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method 2 Redundant code3 Feature envy4 Comments to state the obvious 5 Magic numbers 6 Inconsistent naming conventions 7 Inconsistent formatting 8 Poor exception handling 9 Code duplication with slight variations | t | f | t | 0 | 13354 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 2168 | 13354 | ||
| 922 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | Long method | t | f | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 922 | 8279 | ||
| 693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Poor exception handling 5. Mixing of concerns 6. Inconsistent naming conventions 7. Immodular code 8. Unnecessary commented out code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method2 Feature envy3 Duplicate code4 Poor exception handling5 Mixing of concerns 6 Inconsistent naming conventions 7 Immodular code8 Unnecessary commented out code | t | f | t | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 693 | 6654 | ||
| 598 | YES I found bad smells the bad smells are: 1. Long Method 2. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long Method2 Long Parameter List | t | f | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 598 | 5982 | ||
| 2487 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Code complexity 5. Poor naming conventions 6. Inefficient looping 7. Lack of proper commenting or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Code complexity 5 Poor naming conventions 6 Inefficient looping 7 Lack of proper commenting or documentation | t | f | t | 0 | 14611 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 2487 | 14611 | ||
| 3412 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 3412 | 6662 | ||
| 956 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | 1. long method | t | t | t | 0 | 8539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 956 | 8539 | ||
| 2193 | YES, I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2193 | 13477 | ||
| 2298 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 2298 | 14025 | ||
| 468 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 468 | 4551 | ||
| 883 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | long method | t | t | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 883 | 8029 | ||
| 620 | YES I found bad smells. the bad smells are: long method, feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, feature envy | t | f | t | feature envy. | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 620 | 6215 | |
| 232 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, data class | t | t | t | data class | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 1 | 232 | 2538 | |
| 1486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1486 | 11092 | ||
| 992 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 992 | 9038 | ||
| 393 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | long method | t | t | t | 0 | 3969 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 393 | 3969 | ||
| 1172 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1172 | 10197 | |
| 1194 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | long method | t | t | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 1194 | 10265 | ||
| 1845 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 1845 | 12164 | |
| 859 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 859 | 7898 | ||
| 4334 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | data class, long method | t | t | t | data class | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 4334 | 11444 | |
| 2001 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 2001 | 12710 | ||
| 754 | Yes, I found bad smells. the bad smells are: 1. Commented out code, 2. Long method, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Commented out code, 2 Long method, 3 Feature envy, 4 Duplicate code, 5 Magic numbers, 6 Conditional complexity, 7 Inconsistent naming convention, 8 Hard-coded value | t | f | t | . Commented out code, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 754 | 7039 | |
| 2678 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method | t | t | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2678 | 15253 | ||
| 2575 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2575 | 14915 | ||
| 766 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 766 | 7185 | ||
| 2841 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | long method | t | t | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 2841 | 1663 | ||
| 490 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method | t | f | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 490 | 4881 | ||
| 1592 | YES I found bad smells the bad smells are: 1.Long method, 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
long method | Long method, 2Duplicated Code, 3Complex method, 4Long parameter list, 5Magic numbers, 6Inappropriate comments | t | f | t | 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | 0 | 11396 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 2 | 1592 | 11396 | |
| 2015 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2015 | 12768 | ||
| 486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 486 | 4755 | ||
| 1899 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | 1. long method | t | t | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 1899 | 12355 | ||
| 2130 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | long method, blob | t | t | t | blob | 0 | 13230 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 2130 | 13230 | |
| 1892 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 1892 | 12318 | ||
| 287 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | Long method | t | f | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 287 | 3060 | ||
| 3786 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | long method | t | t | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 3786 | 9536 | ||
| 1197 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeating code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Repeating code3 Feature envy | t | f | t | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1197 | 10271 | ||
| 1623 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | 1 Long Method | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 1 | 1623 | 11490 | ||
| 2696 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2696 | 15319 | |
| 1928 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 12445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 1928 | 12445 | |
| 369 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 369 | 3819 | |
| 394 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method,2 Feature envy,3 Redundant code,4 Complicated control flow,5 Code duplication,6 Poor exception handling | t | f | t | 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 394 | 3978 | |
| 2071 | YES I found bad smells the bad smells are: 1)Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (e.g. hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | )Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (eg hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | t | f | t | 0 | 13025 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2071 | 13025 | ||
| 483 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | long method | t | t | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 483 | 4713 | ||
| 2037 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Lack of comments/documentation 6. Inadequate naming convention 7. Use of raw types 8. Inconsistent formatting/indentation 9. unnecessary temporary variables 10. Empty catch blocks 11. Inconsistent use of logging 12. Use of non-descriptive/misleading variable names 13. Use of wildcard imports 14. Excessive and unnecessary nesting 15. Lack of error handling/exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Magic numbers 5 Lack of comments/documentation 6 Inadequate naming convention 7 Use of raw types 8 Inconsistent formatting/indentation 9 unnecessary temporary variables | t | f | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 2037 | 12838 | ||
| 1587 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 1 | 1587 | 11373 | |
| 5570 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method | t | t | f | long method | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5570 | 8187 | |
| 1837 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 1837 | 12142 | |
| 1338 | YES I found bad smells The bad smells are: 1. Magic numbers 2. Long method 3. Complex logic 4. Feature envy 5. Poor variable naming 6. Repeated code 7. Inconsistent formatting 8. Inefficient use of memory 9. Use of ternary operator 10. Poor exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Magic numbers2 Long method3 Complex logic4 Feature envy5 Poor variable naming6 Repeated code7 Inconsistent formatting8 Inefficient use of memory9 Use of ternary operator | t | f | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 1338 | 10733 | ||
| 1390 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 1390 | 10841 | |
| 86 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 86 | 1216 | ||
| 2750 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Blob" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | 1: blob, 2: long method | t | t | t | 1: blob | 0 | 818 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 2750 | 818 | |
| 900 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex code 5. Multiple method calls within loops 6. Overly complex conditional statements 7. Multiple try-catch blocks with similar structure 8. Unclear variable names 9. Code repetition 10. Inconsistent formatting 11. Comments that do not add value to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Duplicate code4 Complex code5 Multiple method calls within loops6 Overly complex conditional statements7 Multiple try-catch blocks with similar structure8 Unclear variable names9 Code repetition | t | f | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 900 | 8153 | ||
| 1999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 1999 | 12705 | |
| 908 | YES I found bad smells. The bad smells are: Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements | t | f | t | Feature envy, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | 0 | 8202 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 908 | 8202 | |
| 1836 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long Method | t | f | t | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 1836 | 12140 | ||
| 216 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 216 | 2343 | ||
| 495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | long method | t | t | t | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 495 | 5014 | ||
| 5570 | YES I found bad smells The bad smells are: 1. Long method 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2Feature envy | t | f | t | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5570 | 8187 | ||
| 643 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 643 | 6354 | ||
| 1400 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method | t | t | t | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 1400 | 10859 | ||
| 1348 | YES, I found bad smells. the bad smells are: 1.Inappropriate naming, 2. Long method, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | Inappropriate naming, 2 Long method, 3 Feature envy, 4 Nested conditionals, 5 Mixed levels of abstraction, 6 Repeated code, 7 Data clumps, 8 Primitive obsession | t | f | t | .Inappropriate naming, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 1348 | 10753 | |
| 804 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 804 | 7620 | ||
| 1239 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10404 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1239 | 10404 | ||
| 2368 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 2368 | 14301 | ||
| 2053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 2 | 2053 | 12903 | ||
| 891 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 891 | 8095 | ||
| 136 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method, duplicate code | t | t | t | duplicate code | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 136 | 1673 | |
| 904 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 904 | 8176 | ||
| 869 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy | t | f | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 869 | 7948 | ||
| 276 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method 2Feature envy | t | f | t | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 276 | 2964 | ||
| 1739 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code - the same code is repeated multiple times within the method. 4. Magic numbers - the values 1, 11, and 0 are used without explanation. 5. Poor naming - variable names such as "locales" and "slash" are vague and do not clearly explain their purpose or contents. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Feature envy2 Long method3 Duplicate code - the same code is repeated multiple times within the method 4 Magic numbers - the values | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 2 | 1739 | 11836 | ||
| 1397 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1397 | 10854 | |
| 1103 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1103 | 9847 | ||
| 2915 | YES I found bad smells the bad smells are: 1. Long method 2. Repeated code (saveState) 3. Feature envy (multiple method calls on different objects) 4. Inefficient use of flag variables 5. Unused code (clearAttributes() not currently necessary) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method2 Repeated code (saveState)3 Feature envy (multiple method calls on different objects)4 Inefficient use of flag variables5 Unused code (clearAttributes() not currently necessary) | t | f | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2915 | 2253 | ||
| 993 | {"message": "YES I found bad smells", "bad_smells_list": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | long method | t | t | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 1 | 993 | 9070 | ||
| 2666 | YES, I found bad smellsthe bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method | t | f | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 2666 | 15203 | ||
| 2050 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 2 | 2050 | 12885 | ||
| 992 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | 1. long method | t | t | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 992 | 9038 | ||
| 1026 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy (multiple occurrences of using the same object's methods/properties) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method2 Duplicate code3 Feature envy (multiple occurrences of using the same object's methods/properties) | t | f | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1026 | 9361 | ||
| 3381 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 3381 | 6543 | ||
| 2361 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | Long method | t | f | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 2361 | 14251 | ||
| 2131 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method, data class | t | t | t | data class | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 2131 | 13232 | |
| 258 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 2 | 258 | 2807 | |
| 1034 | { "response": "YES I found bad smells", "bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | blob, long method | t | t | t | blob | 0 | 9396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 1034 | 9396 | |
| 940 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 940 | 8460 | |
| 922 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | long method | t | t | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 922 | 8279 | ||
| 780 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7455 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 780 | 7455 | ||
| 99 | {"message":"YES I found bad smells","bad smells are":["1.Long method","2.Complex method","3.Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | 1.long method, 2.complex method, 3.feature envy | t | t | t | 2.complex method, 3.feature envy | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 99 | 1298 | |
| 1443 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 1443 | 10977 | |
| 2164 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 2164 | 13339 | ||
| 173 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 173 | 2041 | |
| 5481 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5481 | 1263 | |
| 366 | YES I found bad smells the bad smells are: 1. Long method 2. Method with multiple responsibilities 3. Feature envy 4. Code duplication (the for loop that allocates columns could be extracted into a separate method) 5. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method2 Method with multiple responsibilities3 Feature envy4 Code duplication (the for loop that allocates columns could be extracted into a separate method)5 Lack of comments/documentation | t | f | t | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 366 | 3740 | ||
| 2571 | YES I found bad smells The bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 2571 | 14900 | ||
| 490 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 490 | 4881 | ||
| 489 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void appendXmlComparison1(SQLBuffer buf, String op, FilterValue lhs, FilterValue rhs) { boolean castrhs = false; Class rc = Filters.wrap(rhs.getType()); int type = 0; if (rhs.isConstant()) { type = getJDBCType(JavaTypes.getTypeCode(rc), false); castrhs = true; } appendXmlExists(buf, lhs); buf.append(" ").append(op).append(" "); buf.append("$"); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("]' PASSING "); appendXmlVar(buf, lhs); buf.append(", "); if (castrhs) appendCast(buf, rhs, type); else rhs.appendTo(buf); buf.append(" AS \""); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("\")"); } |
long method | long method, blob | t | t | t | blob | 0 | 4865 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DB2Dictionary.java/#L682-L717 | 1 | 489 | 4865 | |
| 2781 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2781 | 1122 | ||
| 3795 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 3795 | 9593 | ||
| 1675 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | long method | t | t | t | 0 | 11644 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 1675 | 11644 | ||
| 1925 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1925 | 12434 | ||
| 1515 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1515 | 11164 | |
| 21 | { "answer": "YES I found bad smells", "bad smells are": "1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | 1. long method | t | t | t | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 21 | 682 | ||
| 21 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 21 | 682 | |
| 4605 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 4605 | 12253 | |
| 1959 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 1959 | 12573 | |
| 1543 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1543 | 11243 | |
| 772 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, data class, feature envy | t | t | t | data class, feature envy | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 772 | 7285 | |
| 859 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 859 | 7898 | |
| 732 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 732 | 6885 | ||
| 791 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 791 | 7535 | ||
| 2042 | the bad smells are: 1. Long method 2. Duplicate code 3. Complex conditional logic 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Duplicate code3 Complex conditional logic4 Feature envy | f | f | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 2042 | 12854 | ||
| 1106 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 1106 | 9879 | |
| 1520 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method | t | t | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1520 | 11172 | ||
| 1325 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1325 | 10702 | |
| 1269 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1269 | 10565 | ||
| 1125 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 1125 | 10003 | |
| 2359 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 2359 | 14234 | |
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 240 | 2628 | |
| 982 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 982 | 8859 | ||
| 5531 | YES, I found bad smells the bad smells are: 1. Long method 2. Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Data class | t | f | t | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5531 | 5816 | ||
| 1293 | {"message":"YES I found bad smells","bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1293 | 10623 | |
| 2180 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 2180 | 13413 | ||
| 4048 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 4048 | 10697 | ||
| 258 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method | t | t | t | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 1 | 258 | 2807 | ||
| 1891 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (such as 0.0f, 1.0f) 3. Duplicate code within if statements (within if statement for align variable) 4. Single letter variable names (such as v, n) 5. Complex conditionals within if statements (such as align == 0.0f, align == 1.0f) 6. Inconsistent indentation 7. Use of float instead of double for mathematical operations 8. Lack of comments/documentation explaining the purpose of code or variables 9. Lack of error handling 10. Method performing multiple tasks (calculation and setting of variables) 11. Lack of encapsulation (variables and methods are protected instead of private) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | Long method2 Magic numbers (such as 00f, | t | f | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1891 | 12314 | ||
| 2268 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Magic Numbers (such as the hardcoded value "80" in the method) 4. Inconsistent coding style (such as the mix of tabs and spaces) 5. Code duplication (such as the duplicate calls to LOG.isTraceEnabled()) 6. Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null) 7. Use of deprecated methods (such as FileSystem.get(new URI(), Configuration)) 8. Poor exception handling (such as catching a generic IOException instead of specific exceptions) 9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) 10. Inefficient data structures (such as using nested Map and List structures instead of custom classes) 11. Insufficient comments and documentation (such as not providing javadocs for public methods and classes) 12. Use of raw types (such as Map, List without specifying the types) 13. Poor readability (such as the lack of indentation and the complex nested loops and conditional statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Feature Envy3 Magic Numbers (such as the hardcoded value "80" in the method)4 Inconsistent coding style (such as the mix of tabs and spaces)5 Code duplication (such as the duplicate calls to LOGisTraceEnabled())6 Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null)7 Use of deprecated methods (such as FileSystemget(new URI(), Configuration))8 Poor exception handling (such as catching a generic IOException instead of specific exceptions)9 Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | t | f | t | Configuration))8. Poor exception handling (such as catching a generic IOException instead of specific exceptions)9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2268 | 13747 | |
| 797 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7568 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 797 | 7568 | |
| 1282 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1282 | 10603 | |
| 1913 | YES, I found bad smells The bad smells are: long method, switch statements, feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method, switch statements, feature envy | t | f | t | switch statements, feature envy | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 1913 | 12402 | |
| 1679 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 1679 | 11653 | |
| 2112 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Magic numbers 5. Confusing variable names 6. Lack of comments/documentation 7. Use of nested conditional statements 8. Use of multiple unnecessary checks and comparisons 9. Inefficient if-else structure | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Repeated code3 Feature envy4 Magic numbers5 Confusing variable names6 Lack of comments/documentation7 Use of nested conditional statements8 Use of multiple unnecessary checks and comparisons 9 Inefficient if-else structure | t | f | t | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 2112 | 13189 | ||
| 2257 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 2257 | 13693 | ||
| 577 | { "message": "YES, I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | blob, long method | t | t | t | blob | 0 | 5782 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 577 | 5782 | |
| 2395 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method | t | f | t | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2395 | 14373 | ||
| 3797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 3797 | 9604 | ||
| 2582 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 2582 | 14956 | ||
| 1951 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (Multiple calls to isSet methods on external objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy (Multiple calls to isSet methods on external objects) | t | f | t | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1951 | 12534 | ||
| 1497 | YES I found bad smells The bad smells are: 1. Long method 2. Magic string 3. Repeated code 4. Lack of abstraction 5. Feature envy 6. Large block of code 7. Poorly named variables and methods 8. Explicit type declaration (should use var instead) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method2 Magic string3 Repeated code4 Lack of abstraction5 Feature envy6 Large block of code7 Poorly named variables and methods8 Explicit type declaration (should use var instead) | t | f | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1497 | 11126 | ||
| 5494 | {"output": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 2683 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 2 | 5494 | 2683 |
| 2463 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | long method | t | t | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 2463 | 14551 | ||
| 1665 | { "output": { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1665 | 11622 | |
| 448 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 448 | 4366 | ||
| 5166 | {"message": "YES I found bad smells\nthe bad smells are: 4. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 4. long method | t | t | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5166 | 14457 | ||
| 197 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 197 | 2237 | ||
| 2117 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | 1. long method | t | t | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 2117 | 13197 | ||
| 199 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 199 | 2241 | |
| 995 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | long method, blob | t | t | t | blob | 0 | 9092 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 1 | 995 | 9092 | |
| 1559 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 11300 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1559 | 11300 | |
| 782 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 782 | 7477 | ||
| 1878 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 1878 | 12273 | ||
| 709 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 709 | 6757 | ||
| 653 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 653 | 6389 | ||
| 232 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 2 | 232 | 2538 | |
| 1154 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 1154 | 10137 | |
| 766 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Primitive obsession 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Duplicate code3 Primitive obsession4 Feature envy | t | f | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 766 | 7185 | ||
| 1495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1495 | 11124 | |
| 1338 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 1338 | 10733 | ||
| 2180 | { "message": "YES I found bad smells", "bad_smells": [ { "smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | smell: long method | t | t | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 2180 | 13413 | ||
| 1154 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 1154 | 10137 | |
| 1173 | { "message": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | 1. long method | t | t | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1173 | 10199 | ||
| 1753 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 1 | 1753 | 11865 | |
| 1753 | YES I found bad smells The bad smells are: 1.Long method 2.Magic numbers 3.Coupled design 4.Dead code 5.Inconsistent formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method2Magic numbers3Coupled design4Dead code 5Inconsistent formatting | t | f | t | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 1753 | 11865 | ||
| 1411 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | 1. long method | t | t | t | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 1411 | 10900 | ||
| 1117 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1117 | 9955 | ||
| 1046 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9456 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1046 | 9456 | |
| 1136 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1136 | 10058 | ||
| 1899 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 1899 | 12355 | ||
| 1746 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 1746 | 11853 | |
| 938 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method, blob | t | t | t | blob | 0 | 8427 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 938 | 8427 | |
| 1734 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long Method | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1734 | 11823 | ||
| 502 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method | t | t | t | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 502 | 5087 | ||
| 1440 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 1440 | 10972 | |
| 2011 | { "result": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 2011 | 12750 | |
| 2100 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1. long method | t | t | f | long method | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 2100 | 13158 | |
| 1710 | YES, I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 1710 | 11765 | |
| 1293 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1293 | 10623 | ||
| 5561 | YES I found bad smells the bad smells are listed in this format: 1. Long method, 2. Data class, 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2 Data class, 3 Feature envy | t | f | t | 2. Data class, 3. Feature envy | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5561 | 7769 | |
| 4065 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple return points 4. Excessive comments 5. Nested loops or conditionals 6. Inconsistent formatting and coding style 7. Magic numbers or hardcoded values 8. Violation of the Single Responsibility Principle 9. Complex and unreadable code 10. Lack of documentation or proper naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy3 Multiple return points4 Excessive comments5 Nested loops or conditionals6 Inconsistent formatting and coding style7 Magic numbers or hardcoded values8 Violation of the Single Responsibility Principle9 Complex and unreadable code | t | f | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 4065 | 10729 | ||
| 5710 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | 1. long method | t | t | f | long method | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5710 | 12666 | |
| 2241 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 2241 | 13621 | ||
| 1411 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 1411 | 10900 | |
| 1132 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | 1. long method | t | t | t | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 1 | 1132 | 10040 | ||
| 3968 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10409 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 3968 | 10409 | ||
| 1637 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11527 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 1637 | 11527 | ||
| 2607 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | Long method | t | f | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 2607 | 15030 | ||
| 3797 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 3797 | 9604 | |
| 1906 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 1906 | 12380 | ||
| 2535 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 2535 | 14753 | ||
| 4048 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Primitive obsession 4. Data class 5. Message chains 6. Feature envy 7. Inappropriate intimacy (calling methods from parent class) 8. Mixed levels of abstraction 9. Code repetition (multiple use of "dis" variable) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Primitive obsession4 Data class5 Message chains6 Feature envy7 Inappropriate intimacy (calling methods from parent class)8 Mixed levels of abstraction9 Code repetition (multiple use of "dis" variable) | t | f | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 4048 | 10697 | ||
| 2545 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | 1. long method | t | t | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 2545 | 14790 | ||
| 2132 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 2132 | 13234 | ||
| 1881 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 2 | 1881 | 12286 | ||
| 1188 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 1188 | 10247 | ||
| 2254 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2254 | 13687 | ||
| 2532 | YES, I found bad smells. The bad smells are: (1) Long method, (2) Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | ) Long method, (2) Feature envy | t | f | t | (2) Feature envy. | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 2532 | 14744 | |
| 1901 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 1901 | 12362 | ||
| 4708 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Long Method | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 4708 | 12628 | ||
| 4765 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 4765 | 12825 | ||
| 903 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, data class | t | t | t | data class | 0 | 8170 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 903 | 8170 | |
| 2419 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method, feature envy | t | t | t | feature envy | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 2419 | 14427 | |
| 606 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | 1: long method | t | t | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 606 | 6083 | ||
| 2391 | YES I found bad smells the bad smells are:1.Long method, 2.Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, 2Primitive obsession | t | f | t | 2.Primitive obsession | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 2391 | 14362 | |
| 2340 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 2340 | 14174 | ||
| 1970 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1970 | 12607 | ||
| 1945 | YES I found bad smells The bad smells are: 1. Long method, 2. Data clumps, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method, 2 Data clumps, 3 Feature envy | t | f | t | 2. Data clumps, 3. Feature envy | 0 | 12515 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 1945 | 12515 | |
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 169 | 2032 | ||
| 3937 | YES I found bad smells The bad smells are: 1.Long method, 2.Magic number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method, 2Magic number | t | f | t | 2.Magic number | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 3937 | 10309 | |
| 845 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | 1: long method | t | t | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 845 | 7823 | ||
| 961 | YES, I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Dead code 4. Feature envy 5. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method2 Duplicate code3 Dead code4 Feature envy5 Magic numbers | t | f | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 961 | 8569 | ||
| 1797 | {"message":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 1797 | 12001 | ||
| 575 | { "output": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | data class, long method | t | t | t | data class | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 575 | 5777 | |
| 2381 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent naming conventions 6. Multiple levels of indentation 7. Unnecessary comments 8. Poor exception handling 9. Unnecessary synchronization 10. Use of best effort instead of handling errors properly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Inconsistent naming conventions6 Multiple levels of indentation7 Unnecessary comments8 Poor exception handling 9 Unnecessary synchronization | t | f | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2381 | 14338 | ||
| 5744 | YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5744 | 14137 | |
| 1860 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | 1. long method | t | t | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 1860 | 12221 | ||
| 2361 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 2361 | 14251 | ||
| 1348 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method | t | t | t | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 1348 | 10753 | ||
| 1583 | Yes I found bad smells: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Complex conditional logic (if statements nested within other if statements), 5 Misleading comments (commented out code that is not being used), 6 Manual exception handling rather than using a try-catch block | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | 0 | 11365 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 1583 | 11365 | |
| 2499 | YES, I found bad smells the bad smells are: 1.Long method, 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, 10.Unnecessary null check, 11.Switch statement. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method, 2Unnecessary variable, 3Magic number, 4Duplicate code, 5Inconsistent naming conventions, 6Feature envy, 7Inappropriate comments, 8Unnecessary nesting, 9Exception handling, | t | f | t | 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2499 | 14652 | |
| 1744 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Conditional complexity 5. Inconsistent naming convention 6. Confusing variable names 7. Lack of comments/documentation 8. Use of magic numbers or strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy3 Duplicated code4 Conditional complexity 5 Inconsistent naming convention 6 Confusing variable names 7 Lack of comments/documentation 8 Use of magic numbers or strings | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 1744 | 11849 | ||
| 966 | YES, I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 966 | 8633 | ||
| 1861 | { "output": "YES, I did find bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1861 | 12222 | ||
| 5324 | YES I found bad smells The bad smells are: 1.Feature envy 2.Long method 3.Inconsistent spacing and indentation 4.Magic numbers (PigConfiguration.PIG_ATS_ENABLED) 5.Multiple conditionals in one line (Boolean.parseBoolean calls) 6.Coupled classes (PigATSClient) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Feature envy2Long method3Inconsistent spacing and indentation4Magic numbers (PigConfigurationPIG_ATS_ENABLED)5Multiple conditionals in one line (BooleanparseBoolean calls)6Coupled classes (PigATSClient) | t | f | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 5324 | 14946 | ||
| 3707 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method, 2Feature envy, 3Magic number, 4Throws declaration, 5Overutilization of try-catch blocks, 6Duplicate code, 7Potentially unnecessary variable assignment, 8Inconsistent naming conventions | t | f | t | 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 3707 | 8853 | |
| 4334 | YES We found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 4334 | 11444 | ||
| 1461 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 1461 | 11023 | ||
| 423 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | long method, data class | t | t | t | data class | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 423 | 4247 | |
| 642 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 642 | 6353 | ||
| 544 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1. long method | t | t | f | long method | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 544 | 5546 | |
| 1484 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method | t | t | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 1484 | 11088 | ||
| 662 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 662 | 6455 | ||
| 141 | { "response": "YES I found bad smells", "details": { "the bad smells are": [ "Long method" ] } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | the bad smells are: long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 2 | 141 | 1773 | ||
| 1454 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 1454 | 11007 | ||
| 891 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 891 | 8095 | ||
| 2135 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2135 | 13243 | ||
| 938 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8427 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 938 | 8427 | |
| 2065 | YES I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 2065 | 12987 | ||
| 1588 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 1588 | 11376 | ||
| 650 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | long method | t | t | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 650 | 6383 | ||
| 579 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method, 2Magic numbers, 3 Feature envy | t | f | t | 2.Magic numbers, 3. Feature envy | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 579 | 5784 | |
| 2519 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 2519 | 14706 | ||
| 5777 | {"response": "YES I found bad smells", "bad smells are:": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5777 | 15213 | ||
| 2241 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 2241 | 13621 | ||
| 1431 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1431 | 10955 | ||
| 1147 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | long method, data class | t | t | t | data class | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1147 | 10122 | |
| 2497 | { "input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example { public void doSomething() { // code here } }" }, "output": { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: |
long method | message: yes i found bad smells, detected_bad_smells: 1: long method | t | t | t | message: yes i found bad smells | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 1 | 2497 | 14646 | |
| 996 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Duplicate code, 5 Inconsistent naming conventions | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 996 | 9119 | |
| 2156 | {"message": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | 1. long method | t | t | f | long method | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2156 | 13302 | |
| 1887 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | blob, long method | t | t | t | blob | 0 | 12299 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 1 | 1887 | 12299 | |
| 1692 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Inappropriate exception handling 6. Poor naming conventions 7. Lack of modularity and encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Complex conditional statements 5 Inappropriate exception handling 6 Poor naming conventions 7 Lack of modularity and encapsulation | t | f | t | 0 | 11712 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 1692 | 11712 | ||
| 1363 | YES I found bad smells the bad smells are: 1.Long method 2.Magic numbers 3.Duplicate code 4.Commented code 5.Inconsistent formatting 6.Lack of proper variable naming 7.Complex conditional statements 8.Multiple responsibilities within one method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2Magic numbers3Duplicate code4Commented code5Inconsistent formatting6Lack of proper variable naming7Complex conditional statements8Multiple responsibilities within one method | t | f | t | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1363 | 10780 | ||
| 1809 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12052 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 1809 | 12052 | |
| 795 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicate code in each case of the switch statement 4. Conditional complexity 5. Magic numbers (e.g. "yyyy" for year, "MM" for month, etc.) 6. Feature envy (each case using a different format string instead of using a single method to format the date) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | Long method2 Switch statement3 Duplicate code in each case of the switch statement4 Conditional complexity5 Magic numbers (eg "yyyy" for year, "MM" for month, etc)6 Feature envy (each case using a different format string instead of using a single method to format the date) | t | f | t | "MM" for month, etc.)6. Feature envy (each case using a different format string instead of using a single method to format the date) | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 2 | 795 | 7555 | |
| 335 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 335 | 3439 | ||
| 1957 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Feature envy3 Primitive obsession | t | f | t | 0 | 12568 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 1957 | 12568 | ||
| 361 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 361 | 3699 | ||
| 1931 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method | t | t | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1931 | 12454 | ||
| 1490 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method | t | t | t | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1490 | 11110 | ||
| 993 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 2 | 993 | 9070 | ||
| 513 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method, 2 Duplicate code, 3 Feature envy | t | f | t | 2. Duplicate code, 3. Feature envy | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 513 | 5219 | |
| 1495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1495 | 11124 | |
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 169 | 2032 | ||
| 1959 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | 1 Long Method | t | f | t | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 1959 | 12573 | ||
| 620 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, data class | t | t | t | data class | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 620 | 6215 | |
| 2055 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2055 | 12939 | ||
| 1446 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10983 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 1446 | 10983 | ||
| 1343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10745 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1343 | 10745 | ||
| 2574 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, blob | t | t | t | blob | 0 | 14912 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2574 | 14912 | |
| 1875 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1875 | 12262 | ||
| 5515 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Magic number", "Non-descriptive method or variable names", "Nested block", "Complex conditional logic", "Duplicate code"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | t | t | t | magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5515 | 4260 | |
| 2309 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2309 | 14095 | ||
| 3707 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 3707 | 8853 | |
| 752 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 752 | 7035 | |
| 2148 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 13280 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 2148 | 13280 | |
| 674 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | long method | t | t | t | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 674 | 6568 | ||
| 1826 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 1826 | 12112 | |
| 2274 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 2274 | 13771 | |
| 935 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | 1. long method | t | t | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 935 | 8393 | ||
| 3902 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | long method | t | t | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 1 | 3902 | 10217 | ||
| 1942 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1942 | 12499 | |
| 701 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | long method, blob | t | t | t | blob | 0 | 6688 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 701 | 6688 | |
| 4205 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 2 | 4205 | 11065 | |
| 642 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 642 | 6353 | ||
| 1947 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | f | long method | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 1947 | 12523 | |
| 1544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1544 | 11245 | ||
| 1561 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long Method | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 1561 | 11308 | ||
| 1179 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1179 | 10227 | |
| 1587 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Code duplication 4. Lack of comments/documentation 5. Poor variable naming/descriptive names 6. Code that is difficult to understand/maintain 7. Potential violation of single responsibility principle 8. Potential catch-all exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | Feature envy2 Long method3 Code duplication4 Lack of comments/documentation5 Poor variable naming/descriptive names6 Code that is difficult to understand/maintain7 Potential violation of single responsibility principle 8 Potential catch-all exception handling | t | f | t | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 2 | 1587 | 11373 | ||
| 2089 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | 1. blob, 2. long method | t | t | t | 1. blob | 0 | 13117 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 2089 | 13117 | |
| 3412 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Hard-coded strings 4. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Magic numbers3 Hard-coded strings4 Code duplication | t | f | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 3412 | 6662 | ||
| 1679 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method, 2 Duplicated code, 3 Conditional complexity, 4 Long parameter list | t | f | t | 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 1679 | 11653 | |
| 1390 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 1390 | 10841 | |
| 885 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Repeated code 4. Data clump 5. Feature envy 6. Assert statements 7. Null checks 8. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers3 Repeated code4 Data clump5 Feature envy6 Assert statements7 Null checks8 Incomplete error handling | t | f | t | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 885 | 8053 | ||
| 2750 | YES I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 818 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 2750 | 818 | ||
| 1459 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | feature envy, long method | t | t | t | feature envy | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1459 | 11020 | |
| 2131 | YES I found bad smells the bad smells are: 1. Duplicate code (creating multiple nodes) 2. Long method (contains multiple operations) 3. Feature envy (NodeManager.add method being used frequently) 4. Primitive obsession (defining variable types as double and integer instead of creating custom objects) 5. Catch and hide exception (no proper handling of the exception) 6. Lack of readability and organization, making it difficult to understand the flow of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | Duplicate code (creating multiple nodes)2 Long method (contains multiple operations)3 Feature envy (NodeManageradd method being used frequently)4 Primitive obsession (defining variable types as double and integer instead of creating custom objects)5 Catch and hide exception (no proper handling of the exception)6 Lack of readability and organization, making it difficult to understand the flow of the code | t | f | t | making it difficult to understand the flow of the code. | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 2131 | 13232 | |
| 1420 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long Method | t | f | t | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1420 | 10928 | ||
| 28 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | data class, long method | t | t | t | data class | 0 | 712 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 28 | 712 | |
| 445 | YES I found bad smells. The bad smells are: 1. Long method 2. Redundant code 3. Code duplication 4. Complex control flow 5. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | Long method 2 Redundant code 3 Code duplication 4 Complex control flow 5 Inconsistent naming conventions | t | f | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 2 | 445 | 4346 | ||
| 1817 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Temporary fields 4. Duplicate code 5. Catch-all exception handling 6. Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy3 Temporary fields4 Duplicate code5 Catch-all exception handling6 Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | t | f | t | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1817 | 12088 | ||
| 971 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 971 | 8713 | |
| 1830 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method | t | t | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 1830 | 12121 | ||
| 1038 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | long method | t | t | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1038 | 9410 | ||
| 2130 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13230 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 2130 | 13230 | ||
| 1928 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 12445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 1928 | 12445 | ||
| 2548 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops/cyclomatic complexity 4. Inconsistent indentation 5. Complex conditional statements 6. Magic numbers/unnamed variables 7. Unused/unnecessary variables 8. Lack of comments/documentation 9. Use of null values 10. Large class/object 11. Inefficient use of data structures 12. Code duplication 13. Unclear naming conventions for variables/methods 14. Multiple return statements within a method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy3 Nested loops/cyclomatic complexity4 Inconsistent indentation5 Complex conditional statements6 Magic numbers/unnamed variables7 Unused/unnecessary variables 8 Lack of comments/documentation 9 Use of null values | t | f | t | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 2548 | 14793 | ||
| 5324 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | 1. long method | t | t | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 5324 | 14946 | ||
| 1810 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long Method | t | f | t | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1810 | 12056 | ||
| 423 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 423 | 4247 | ||
| 1523 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 1523 | 11179 | ||
| 1800 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long Method | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 1800 | 12011 | ||
| 2135 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method, 2 Feature envy, 3 Shotgun surgery, 4 Duplicate code | t | f | t | 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2135 | 13243 | |
| 461 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | long method | t | t | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 1 | 461 | 4463 | ||
| 2633 | YES I found bad smells the bad smells are: 1.Long method, 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method, 2Large parameter list, 3Magic numbers, 4Data class, 5Switch statement, 6Duplicate code | t | f | t | 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 2633 | 15109 | |
| 880 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method, blob | t | t | t | blob | 0 | 8016 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 880 | 8016 | |
| 199 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 199 | 2241 | ||
| 2070 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 2070 | 13017 | ||
| 1763 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the for loop) 4. Confusing logic/naming (headerValue vs hdr) 5. Magic numbers (CONFIG_PREFIX_OPTIONAL + ".") 6. Nested loops 7. Use of isEmpty() instead of checking for size() == 0 8. Code comments indicating potential issues or bad practices 9. Poor exception handling (consistently throwing the same exception) 10. Possible violation of Single Responsibility Principle (SRP), as the method is responsible for multiple tasks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Duplicate code (in the for loop)4 Confusing logic/naming (headerValue vs hdr)5 Magic numbers (CONFIG_PREFIX_OPTIONAL + "")6 Nested loops7 Use of isEmpty() instead of checking for size() == 08 Code comments indicating potential issues or bad practices9 Poor exception handling (consistently throwing the same exception) | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1763 | 11896 | ||
| 1590 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | 1 Long Method | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 1590 | 11387 | ||
| 1486 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1486 | 11092 | |
| 2198 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Lack of proper error handling 5. Excessive amount of parameters 6. Excessive commenting 7. Lack of proper abstraction 8. Use of primitive types instead of objects 9. Inconsistent naming conventions 10. Excessive code duplication or repetition | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method 2 Feature envy 3 Nested loops 4 Lack of proper error handling 5 Excessive amount of parameters 6 Excessive commenting 7 Lack of proper abstraction 8 Use of primitive types instead of objects 9 Inconsistent naming conventions | t | f | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2198 | 13492 | ||
| 1437 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1437 | 10965 | |
| 882 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 882 | 8025 | ||
| 1732 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Duplicate code 6. Magic numbers (e.g. 32) 7. Poor naming (e.g. variables like "ent" and "iter") 8. Indicators of complex or confusing logic (e.g. multiple if statements checking for different conditions) 9. Comments left in the code (e.g. promise to remove println) 10. Use of non-descriptive or ambiguous variable names (e.g. "dst" or "src") 11. Lack of proper exception handling (e.g. if (ent.getType() == LogEntry.Type.TXN) throws an unchecked exception). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | Long method2 Feature envy 3 Data class4 Primitive obsession5 Duplicate code6 Magic numbers (eg 32)7 Poor naming (eg variables like "ent" and "iter")8 Indicators of complex or confusing logic (eg multiple if statements checking for different conditions)9 Comments left in the code (eg promise to remove println) | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 1732 | 11821 | ||
| 1441 | YES I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 1441 | 10974 | ||
| 1142 | YES I found bad smells * 1. Long method * 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method* 2 Feature envy | t | f | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1142 | 10095 | ||
| 2177 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 2177 | 13408 | ||
| 2345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 2345 | 14192 | ||
| 569 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 569 | 5727 | ||
| 1101 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | blob, long method | t | t | t | blob | 0 | 9839 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1101 | 9839 | |
| 407 | YES, I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Long parameter list3 Feature envy | t | f | t | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 407 | 4155 | ||
| 5271 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | long method | t | t | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5271 | 14741 | ||
| 1745 | { "message": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 1745 | 11851 | ||
| 729 | YES I found bad smells1. Long method 2. Feature envy 3. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy 3 Message chain | t | f | t | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 729 | 6854 | ||
| 1677 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | 1 Long Method | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 1677 | 11648 | ||
| 1559 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if conditions for different instances of Length) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Duplicate code (in the if conditions for different instances of Length) | t | f | t | 0 | 11300 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1559 | 11300 | ||
| 3987 | { "response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
long method | long method, blob | t | t | t | blob | 0 | 10502 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 1 | 3987 | 10502 | |
| 387 | YES I found bad smells The bad smells are: 1. Long Method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long Method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 387 | 3944 | |
| 1145 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method | t | t | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 1145 | 10111 | ||
| 371 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 371 | 3852 | |
| 2110 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | long method | t | t | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 2110 | 13182 | ||
| 872 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Repeated logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Repeated logic | t | f | t | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 2 | 872 | 7980 | ||
| 5515 | YES I found bad smells the bad smells are: Long method, Feature envy, Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, Feature envy, Data class | t | f | t | Feature envy, Data class | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5515 | 4260 | |
| 2597 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 2597 | 15009 | |
| 379 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Switch statement 4. Possible lack of comparison strategy for different cases 5. Use of instanceof operator 6. Use of type-unsafe comparison between different types (numbers and strings) 7. Lack of proper comments/documentation 8. Unclear and potentially misleading variable names such as "o1" and "o2" 9. Potential for code duplication due to nested if/else statements 10. Use of raw type Collection instead of parametrized type | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method2 Feature envy3 Switch statement4 Possible lack of comparison strategy for different cases5 Use of instanceof operator6 Use of type-unsafe comparison between different types (numbers and strings)7 Lack of proper comments/documentation8 Unclear and potentially misleading variable names such as "o | t | f | t | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 379 | 3905 | ||
| 632 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 632 | 6293 | ||
| 590 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | long method, data class | t | t | t | data class | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 590 | 5890 | |
| 3557 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 7777 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 3557 | 7777 | |
| 1555 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 1555 | 11276 | ||
| 4398 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 4398 | 11629 | ||
| 958 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 958 | 8556 | ||
| 462 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | 1. long method | t | t | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 462 | 4467 | ||
| 1513 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1513 | 11161 | |
| 2299 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | \n1. long method | t | t | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 2299 | 14028 | ||
| 729 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 729 | 6854 | |
| 5189 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14509 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5189 | 14509 | |
| 2115 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method, data class | t | t | t | data class | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 2115 | 13193 | |
| 1842 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 1842 | 12151 | |
| 754 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 754 | 7039 | ||
| 2304 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | long method | t | t | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 2304 | 14061 | ||
| 1716 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1716 | 11781 | ||
| 5765 | } YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14654 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5765 | 14654 | |
| 1041 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy. | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1041 | 9429 | |
| 866 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | 1. long method, 2. blob | t | t | t | 2. blob | 0 | 7932 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 866 | 7932 | |
| 2400 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14379 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 2400 | 14379 | |
| 964 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method detected" }, { "2. Feature Envy": "Feature Envy detected" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method: long method detected, 2. feature envy: feature envy detected | t | t | t | 2. feature envy: feature envy detected | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 964 | 8595 | |
| 984 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | long method, blob | t | t | t | blob | 0 | 8875 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 1 | 984 | 8875 | |
| 1859 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1859 | 12219 | ||
| 605 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 605 | 6050 | ||
| 1314 | YES I found bad smells the bad smells are: 1. Long method 2. Loss of cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Loss of cohesion | t | f | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1314 | 10686 | ||
| 1923 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1923 | 12426 | ||
| 1515 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1515 | 11164 | ||
| 466 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | long method | t | t | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 1 | 466 | 4523 | ||
| 2345 | {"response": "YES, I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 2345 | 14192 | ||
| 1400 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method, 2 Duplicate code | t | f | t | 2. Duplicate code. | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 1400 | 10859 | |
| 309 | {"message": "YES, I found bad smells", "bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
long method | blob, long method | t | t | t | blob | 0 | 3204 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 1 | 309 | 3204 | |
| 257 | { "response": "YES, I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 2 | 257 | 2777 | |
| 383 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 383 | 3920 | ||
| 2132 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 2132 | 13234 | |
| 141 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 1 | 141 | 1773 | ||
| 970 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 970 | 8695 | ||
| 429 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 429 | 4276 | ||
| 5649 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method | t | f | t | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5649 | 11206 | ||
| 1197 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | long method, data class | t | t | t | data class | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1197 | 10271 |
(1204 rows)